

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


GO
/*
The column [sEMeeting].[tMeetingTypeMaster].[Name] is being dropped, data loss could occur.
*/

IF EXISTS (select top 1 1 from [sEMeeting].[tMeetingTypeMaster])
    RAISERROR (N'Rows were detected. The schema update is terminating because data loss might occur.', 16, 127) WITH NOWAIT

GO
/*
The column [sEMeeting].[tOnlineMeetingAttendance].[OnlineLearningId] is being dropped, data loss could occur.

The column [sEMeeting].[tOnlineMeetingAttendance].[OnlineMeetingId] on table [sEMeeting].[tOnlineMeetingAttendance] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue you must either: add a default value to the column, mark it as allowing NULL values, or enable the generation of smart-defaults as a deployment option.
*/

IF EXISTS (select top 1 1 from [sEMeeting].[tOnlineMeetingAttendance])
    RAISERROR (N'Rows were detected. The schema update is terminating because data loss might occur.', 16, 127) WITH NOWAIT

GO
/*
The column [sPurchase].[tGoodsReceivedNote].[DepartmentBranchId] is being dropped, data loss could occur.
*/

IF EXISTS (select top 1 1 from [sPurchase].[tGoodsReceivedNote])
    RAISERROR (N'Rows were detected. The schema update is terminating because data loss might occur.', 16, 127) WITH NOWAIT

GO
/*
The column [sPurchase].[tInvoiceGenerate].[InvoiceGenerateId] is being dropped, data loss could occur.
*/

IF EXISTS (select top 1 1 from [sPurchase].[tInvoiceGenerate])
    RAISERROR (N'Rows were detected. The schema update is terminating because data loss might occur.', 16, 127) WITH NOWAIT

GO
PRINT N'Dropping Procedure [sEMeeting].[pOnlineMeetingAdd]...';


GO
DROP PROCEDURE [sEMeeting].[pOnlineMeetingAdd];


GO
PRINT N'Dropping Procedure [sPurchase].[pGoodsReceivedNoteAdd]...';


GO
DROP PROCEDURE [sPurchase].[pGoodsReceivedNoteAdd];


GO
PRINT N'Dropping Procedure [sPurchase].[pPurchaseOrderAdd]...';


GO
DROP PROCEDURE [sPurchase].[pPurchaseOrderAdd];


GO
PRINT N'Dropping Procedure [sPurchase].[pPurchaseRequestAdd]...';


GO
DROP PROCEDURE [sPurchase].[pPurchaseRequestAdd];


GO
PRINT N'Dropping Procedure [sPurchase].[pQuotationRequestAdd]...';


GO
DROP PROCEDURE [sPurchase].[pQuotationRequestAdd];


GO
PRINT N'Dropping Procedure [sPurchase].[pSalesReturnAdd]...';


GO
DROP PROCEDURE [sPurchase].[pSalesReturnAdd];


GO
PRINT N'Dropping Procedure [sPurchase].[pInvoiceGenerateAdd]...';


GO
DROP PROCEDURE [sPurchase].[pInvoiceGenerateAdd];


GO
PRINT N'Dropping Procedure [sPurchase].[pQualityCheckAdd]...';


GO
DROP PROCEDURE [sPurchase].[pQualityCheckAdd];


GO
PRINT N'Dropping Procedure [sEMeeting].[pOnlineMeetingScopeAdd]...';


GO
DROP PROCEDURE [sEMeeting].[pOnlineMeetingScopeAdd];


GO
PRINT N'Dropping Procedure [sEMeeting].[pOnlineMeetingScopeGet]...';


GO
DROP PROCEDURE [sEMeeting].[pOnlineMeetingScopeGet];


GO
PRINT N'Dropping Procedure [sPurchase].[InvoiceGenerateDelete]...';


GO
DROP PROCEDURE [sPurchase].[InvoiceGenerateDelete];


GO
PRINT N'Dropping User-Defined Table Type [sEMeeting].[OnlineMeetingResourceDetailType]...';


GO
DROP TYPE [sEMeeting].[OnlineMeetingResourceDetailType];


GO
PRINT N'Dropping User-Defined Table Type [sEMeeting].[OnlineMeetingScopeDetailType]...';


GO
DROP TYPE [sEMeeting].[OnlineMeetingScopeDetailType];


GO
PRINT N'Dropping User-Defined Table Type [sPurchase].[GoodsReceivedNoteDetailType]...';


GO
DROP TYPE [sPurchase].[GoodsReceivedNoteDetailType];


GO
PRINT N'Dropping User-Defined Table Type [sPurchase].[InvoiceGenerateDetailType]...';


GO
DROP TYPE [sPurchase].[InvoiceGenerateDetailType];


GO
PRINT N'Dropping User-Defined Table Type [sPurchase].[PurchaseOrderDetailType]...';


GO
DROP TYPE [sPurchase].[PurchaseOrderDetailType];


GO
PRINT N'Dropping User-Defined Table Type [sPurchase].[PurchaseRequestDetailType]...';


GO
DROP TYPE [sPurchase].[PurchaseRequestDetailType];


GO
PRINT N'Dropping User-Defined Table Type [sPurchase].[QualityCheckDetailType]...';


GO
DROP TYPE [sPurchase].[QualityCheckDetailType];


GO
PRINT N'Dropping User-Defined Table Type [sPurchase].[QuotationRequestDetailType]...';


GO
DROP TYPE [sPurchase].[QuotationRequestDetailType];


GO
PRINT N'Dropping User-Defined Table Type [sPurchase].[SalesReturnDetailType]...';


GO
DROP TYPE [sPurchase].[SalesReturnDetailType];


GO
PRINT N'Creating User-Defined Table Type [sEMeeting].[OnlineMeetingResourceDetailType]...';


GO
CREATE TYPE [sEMeeting].[OnlineMeetingResourceDetailType] AS TABLE (
    [OnlineMeetingId] BIGINT          NOT NULL,
    [ResourceTypeId]  SMALLINT        NOT NULL,
    [ResourcePath]    NVARCHAR (2000) NOT NULL,
    [IsObsolete]      BIT             NULL,
    [CreatedUserId]   BIGINT          NOT NULL,
    [CreatedDateTime] DATETIME        NOT NULL,
    [UpdatedUserId]   BIGINT          NULL,
    [UpdatedDateTime] DATETIME        NULL);


GO
PRINT N'Creating User-Defined Table Type [sEMeeting].[OnlineMeetingScopeDetailType]...';


GO
CREATE TYPE [sEMeeting].[OnlineMeetingScopeDetailType] AS TABLE (
    [AutoId]            BIGINT   NOT NULL,
    [OnlineMeetingId]   BIGINT   NOT NULL,
    [ScopeSourceTypeId] SMALLINT NOT NULL,
    [ScopeSourceId]     BIGINT   NOT NULL,
    [IsObsolete]        BIT      NULL,
    [AssigneeId]        TINYINT  NOT NULL,
    [CreatedUserId]     BIGINT   NOT NULL,
    [CreatedDateTime]   DATETIME NOT NULL,
    [UpdatedUserId]     BIGINT   NULL,
    [UpdatedDateTime]   DATETIME NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[GoodsReceivedNoteDetailType]...';


GO
CREATE TYPE [sPurchase].[GoodsReceivedNoteDetailType] AS TABLE (
    [Id]                      BIGINT          NOT NULL,
    [OrgGroupId]              SMALLINT        NOT NULL,
    [PurchaseRequestDetailId] BIGINT          NOT NULL,
    [UnitTypeId]              BIGINT          NOT NULL,
    [CategoryId]              BIGINT          NOT NULL,
    [SubCategoryId]           BIGINT          NOT NULL,
    [StockItemId]             BIGINT          NOT NULL,
    [POQty]                   DECIMAL (12, 2) NOT NULL,
    [ReceivedQty]             DECIMAL (12, 2) NOT NULL,
    [PreviousGRNQty]          DECIMAL (12, 2) NOT NULL,
    [UnitPrice]               DECIMAL (12, 2) NOT NULL,
    [Remark]                  NVARCHAR (300)  NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[InvoiceGenerateDetailType]...';


GO
CREATE TYPE [sPurchase].[InvoiceGenerateDetailType] AS TABLE (
    [Id]                        BIGINT          NOT NULL,
    [OrgGroupId]                SMALLINT        NOT NULL,
    [InvoiceGenerateId]         BIGINT          NOT NULL,
    [GoodsReceivedNoteDetailId] BIGINT          NOT NULL,
    [UnitTypeId]                BIGINT          NOT NULL,
    [CategoryId]                BIGINT          NOT NULL,
    [SubCategoryId]             BIGINT          NOT NULL,
    [StockItemId]               BIGINT          NOT NULL,
    [POQty]                     DECIMAL (12, 2) NOT NULL,
    [ReceivedQty]               DECIMAL (12, 2) NOT NULL,
    [AcceptedQty]               DECIMAL (12, 2) NOT NULL,
    [RejectedQty]               DECIMAL (12, 2) NOT NULL,
    [UnitPrice]                 DECIMAL (12, 2) NOT NULL,
    [ReasonForRejection]        NVARCHAR (300)  NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[PurchaseOrderDetailType]...';


GO
CREATE TYPE [sPurchase].[PurchaseOrderDetailType] AS TABLE (
    [Id]                      BIGINT          NOT NULL,
    [OrgGroupId]              SMALLINT        NOT NULL,
    [PurchaseRequestDetailId] BIGINT          NOT NULL,
    [StockItemId]             BIGINT          NOT NULL,
    [TotalQty]                DECIMAL (12, 2) NOT NULL,
    [Remark]                  NVARCHAR (300)  NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[PurchaseRequestDetailType]...';


GO
CREATE TYPE [sPurchase].[PurchaseRequestDetailType] AS TABLE (
    [Id]           BIGINT          NOT NULL,
    [OrgGroupId]   SMALLINT        NOT NULL,
    [StockItemId]  BIGINT          NOT NULL,
    [RequestedQty] DECIMAL (12, 2) NOT NULL,
    [Remark]       NVARCHAR (300)  NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[QualityCheckDetailType]...';


GO
CREATE TYPE [sPurchase].[QualityCheckDetailType] AS TABLE (
    [Id]                        BIGINT          NOT NULL,
    [OrgGroupId]                SMALLINT        NOT NULL,
    [GoodsReceivedNoteDetailId] BIGINT          NOT NULL,
    [UnitTypeId]                BIGINT          NOT NULL,
    [CategoryId]                BIGINT          NOT NULL,
    [SubCategoryId]             BIGINT          NOT NULL,
    [StockItemId]               BIGINT          NOT NULL,
    [POQty]                     DECIMAL (12, 2) NOT NULL,
    [ReceivedQty]               DECIMAL (12, 2) NOT NULL,
    [AcceptedQty]               DECIMAL (12, 2) NOT NULL,
    [RejectedQty]               DECIMAL (12, 2) NOT NULL,
    [ReasonForRejection]        NVARCHAR (300)  NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[QuotationRequestDetailType]...';


GO
CREATE TYPE [sPurchase].[QuotationRequestDetailType] AS TABLE (
    [Id]                      BIGINT          NOT NULL,
    [OrgGroupId]              SMALLINT        NOT NULL,
    [PurchaseRequestDetailId] BIGINT          NOT NULL,
    [StockItemId]             BIGINT          NOT NULL,
    [RequestedQty]            DECIMAL (12, 2) NOT NULL,
    [Remark]                  NVARCHAR (300)  NULL,
    [TargetPrice]             DECIMAL (12, 2) NOT NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[SalesReturnDetailType]...';


GO
CREATE TYPE [sPurchase].[SalesReturnDetailType] AS TABLE (
    [Id]                        BIGINT          NOT NULL,
    [OrgGroupId]                SMALLINT        NOT NULL,
    [GoodsReceivedNoteDetailId] BIGINT          NOT NULL,
    [UnitTypeId]                BIGINT          NOT NULL,
    [CategoryId]                BIGINT          NOT NULL,
    [SubCategoryId]             BIGINT          NOT NULL,
    [StockItemId]               BIGINT          NOT NULL,
    [POQty]                     DECIMAL (12, 2) NOT NULL,
    [ReceivedQty]               DECIMAL (12, 2) NOT NULL,
    [RejectedQty]               DECIMAL (12, 2) NOT NULL,
    [CreditNoteIssueDate]       DATETIME        NULL,
    [ReasonForRejection]        NVARCHAR (300)  NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[ApprovingAuthorityType]...';


GO
CREATE TYPE [sPurchase].[ApprovingAuthorityType] AS TABLE (
    [AuthoritySourceTypeId] SMALLINT NOT NULL,
    [AuthoritySourceId]     BIGINT   NOT NULL,
    [OrgId]                 SMALLINT NOT NULL,
    [WfFunctionalityId]     SMALLINT NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[DocumentManagementType]...';


GO
CREATE TYPE [sPurchase].[DocumentManagementType] AS TABLE (
    [OrgGroupId]  SMALLINT       NOT NULL,
    [SourceId]    BIGINT         NOT NULL,
    [FileName]    VARCHAR (50)   NULL,
    [Size]        BIGINT         NULL,
    [DocumentUrl] NVARCHAR (200) NOT NULL);


GO
PRINT N'Altering Table [sCertificate].[tFirstTrial]...';


GO
ALTER TABLE [sCertificate].[tFirstTrial]
    ADD [LastExamName]     NVARCHAR (150) NULL,
        [ObtainedMark]     NVARCHAR (100) NULL,
        [AdditionalRemark] NVARCHAR (MAX) NULL;


GO
PRINT N'Altering Table [sCommunication].[tCircular]...';


GO
ALTER TABLE [sCommunication].[tCircular]
    ADD [IsConsent] BIT CONSTRAINT [DF_tCircular_IsConsent] DEFAULT ((0)) NULL;


GO
PRINT N'Altering Table [sCommunication].[tDailyThoughtAssign]...';


GO
ALTER TABLE [sCommunication].[tDailyThoughtAssign] ALTER COLUMN [DailyThoughtId] NVARCHAR (100) NOT NULL;


GO
PRINT N'Altering Table [sEMeeting].[tMeetingTypeMaster]...';


GO
ALTER TABLE [sEMeeting].[tMeetingTypeMaster] DROP COLUMN [Name];


GO
ALTER TABLE [sEMeeting].[tMeetingTypeMaster]
    ADD [Code]        NVARCHAR (10)  NULL,
        [Title]       NVARCHAR (50)  NULL,
        [OrderIndex]  INT            NULL,
        [Description] NVARCHAR (MAX) NULL;


GO
PRINT N'Altering Table [sEMeeting].[tOnlineMeeting]...';


GO
ALTER TABLE [sEMeeting].[tOnlineMeeting]
    ADD [AssigneeId]        TINYINT  NULL,
        [StartDateTime]     DATETIME NULL,
        [EndDateTime]       DATETIME NULL,
        [IsTrackAttendance] BIT      NULL;


GO
PRINT N'Starting rebuilding table [sEMeeting].[tOnlineMeetingAttendance]...';


GO
BEGIN TRANSACTION;

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

CREATE TABLE [sEMeeting].[tmp_ms_xx_tOnlineMeetingAttendance] (
    [AutoId]                  BIGINT   IDENTITY (1, 1) NOT NULL,
    [OnlineMeetingId]         BIGINT   NOT NULL,
    [ParticipantSourceTypeId] SMALLINT NOT NULL,
    [ParticipantSourceId]     BIGINT   NOT NULL,
    [IsPresent]               BIT      NULL,
    [FirstInDateTime]         DATETIME NOT NULL,
    [LastOutDateTime]         DATETIME NULL,
    [IsLoggedIn]              BIT      NULL,
    CONSTRAINT [tmp_ms_xx_constraint_PK_tOnlineMeetingAttendance1] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);

IF EXISTS (SELECT TOP 1 1 
           FROM   [sEMeeting].[tOnlineMeetingAttendance])
    BEGIN
        SET IDENTITY_INSERT [sEMeeting].[tmp_ms_xx_tOnlineMeetingAttendance] ON;
        INSERT INTO [sEMeeting].[tmp_ms_xx_tOnlineMeetingAttendance] ([AutoId], [ParticipantSourceTypeId], [ParticipantSourceId], [IsPresent], [FirstInDateTime], [LastOutDateTime], [IsLoggedIn])
        SELECT   [AutoId],
                 [ParticipantSourceTypeId],
                 [ParticipantSourceId],
                 [IsPresent],
                 [FirstInDateTime],
                 [LastOutDateTime],
                 [IsLoggedIn]
        FROM     [sEMeeting].[tOnlineMeetingAttendance]
        ORDER BY [AutoId] ASC;
        SET IDENTITY_INSERT [sEMeeting].[tmp_ms_xx_tOnlineMeetingAttendance] OFF;
    END

DROP TABLE [sEMeeting].[tOnlineMeetingAttendance];

EXECUTE sp_rename N'[sEMeeting].[tmp_ms_xx_tOnlineMeetingAttendance]', N'tOnlineMeetingAttendance';

EXECUTE sp_rename N'[sEMeeting].[tmp_ms_xx_constraint_PK_tOnlineMeetingAttendance1]', N'PK_tOnlineMeetingAttendance', N'OBJECT';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Altering Table [sEMeeting].[tOnlineMeetingScope]...';


GO
ALTER TABLE [sEMeeting].[tOnlineMeetingScope]
    ADD [AssigneeId] TINYINT NULL;


GO
PRINT N'Altering Table [sPurchase].[tGoodsReceivedNote]...';


GO
ALTER TABLE [sPurchase].[tGoodsReceivedNote] DROP COLUMN [DepartmentBranchId];


GO
PRINT N'Altering Table [sPurchase].[tInvoiceGenerate]...';


GO
ALTER TABLE [sPurchase].[tInvoiceGenerate] DROP COLUMN [InvoiceGenerateId];


GO
PRINT N'Creating Table [sPurchase].[tDocumentManagement]...';


GO
CREATE TABLE [sPurchase].[tDocumentManagement] (
    [AutoId]          BIGINT         IDENTITY (1, 1) NOT NULL,
    [OrgGroupId]      SMALLINT       NOT NULL,
    [SourceId]        BIGINT         NOT NULL,
    [SourceTypeId]    SMALLINT       NOT NULL,
    [UserId]          BIGINT         NOT NULL,
    [FileName]        VARCHAR (50)   NULL,
    [Size]            BIGINT         NULL,
    [DocumentUrl]     NVARCHAR (200) NOT NULL,
    [CreatedUserId]   BIGINT         NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL,
    [IpAddress]       NVARCHAR (50)  NULL,
    CONSTRAINT [PK_sPurchase]].[tDocumentManagement] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Default Constraint unnamed constraint on [sWf].[tWfSetup]...';


GO
ALTER TABLE [sWf].[tWfSetup]
    ADD DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Refreshing View [sCertificate].[vPrintTemplateFirstTrialCertificate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[vPrintTemplateFirstTrialCertificate]';


GO
PRINT N'Altering Function [sConfig].[fDisplayFieldGet]...';


GO
ALTER FUNCTION [sConfig].[fDisplayFieldGet](@rOrgId int)
RETURNS  @List TABLE (
		-- DisplayFieldId smallint,
		 IsDisplayFamilyDetail bit,
		 IsDisplaySiblingDetail bit,
		 IsDisplayPassportDetail bit,
		 IsDisplayBankDetail bit,
		 IsDisplayCBSEREGDetail bit,
		 IsDisplayCollegeDetail bit,
		 IsDisplayGOVREGNoDetail bit,
		 IsDisplayHealthDetail bit,
		 IsDisplayTransportDetail bit,
		 IsDisplayHostelDetail bit,
		 IsDisplayClubDetail bit,
		 IsDisplaySSCResultDDetail bit,
		 IsDisplayHSCResultDetail bit,
		 IsDisplayJeeDetail bit,
		 IsDisplayDiplomaDetail bit,
		 IsDisplayClassTeacherDetail bit,
		 IsDisplayAdmissionDetail bit,
		 OrgId smallint 
)  WITH EXECUTE AS CALLER
AS 
BEGIN

    declare @rDisplayFieldId smallint 
    declare @rIsDisplayFamilyDetail bit
    declare @rIsDisplaySiblingDetail bit 
    declare @rIsDisplayPassportDetail bit
    declare @rIsDisplayBankDetail bit 
    declare @rIsDisplayCBSEREGDetail bit 
    declare @rIsDisplayCollegeDetail bit 
    declare @rIsDisplayGOVREGNoDetail bit 
    declare @rIsDisplayHealthDetail bit 
    declare @rIsDisplayTransportDetail bit 
    declare @rIsDisplayHostelDetail bit 
    declare @rIsDisplayClubDetail bit 
    declare @rIsDisplaySSCResultDDetail bit 
    declare @rIsDisplayHSCResultDetail bit 
    declare @rIsDisplayJeeDetail bit 
    declare @rIsDisplayDiplomaDetail bit 
    declare @rIsDisplayClassTeacherDetail bit
	declare @rIsDisplayAdmissionDetail bit

	select @rIsDisplayFamilyDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 101
	select @rIsDisplaySiblingDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 102
	select @rIsDisplayPassportDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 103
	select @rIsDisplayBankDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 104
	select @rIsDisplayCBSEREGDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 105
	select @rIsDisplayCollegeDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 106
	select @rIsDisplayGOVREGNoDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 107
	select @rIsDisplayHealthDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 108
	select @rIsDisplayTransportDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 109
	select @rIsDisplayHostelDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 110
	select @rIsDisplayClubDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 111
	select @rIsDisplaySSCResultDDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 112
	select @rIsDisplayHSCResultDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 113
	select @rIsDisplayJeeDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 114
	select @rIsDisplayDiplomaDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 115
	select @rIsDisplayClassTeacherDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 117
	select @rIsDisplayAdmissionDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1225
		 
	 	
	INSERT INTO @List 
	SELECT 
			
			
		   (CASE WHEN @rIsDisplayFamilyDetail Is Null THEN  0 ELSE 1 END) AS IsDisplayFamilyDetail,
		   (CASE WHEN @rIsDisplaySiblingDetail Is Null THEN 0 ELSE 1 END)AS IsDisplaySiblingDetail,
		   (CASE WHEN @rIsDisplayPassportDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayPassportDetail,
		   (CASE WHEN @rIsDisplayBankDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayBankDetail,
		   (CASE WHEN @rIsDisplayCBSEREGDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayCBSEREGDetail,
		   (CASE WHEN @rIsDisplayCollegeDetail Is Null THEN 0  ELSE 1 END)AS IsIsDisplayCollegeDetail,
		   (CASE WHEN @rIsDisplayGOVREGNoDetail Is Null THEN 0 ELSE  1 END)AS IsDisplayGOVREGNoDetail,
		   (CASE WHEN @rIsDisplayHealthDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayHealthDetail,
		   (CASE WHEN @rIsDisplayTransportDetail Is Null THEN 0 ELSE  1 END)AS IsDisplayTransportDetail,
		   (CASE WHEN @rIsDisplayHostelDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayHostelDetail,
		   (CASE WHEN @rIsDisplayClubDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayClubDetail,
		   (CASE WHEN @rIsDisplaySSCResultDDetail Is Null THEN 0  ELSE 1 END)AS IsDisplaySSCResultDDetail,
		   (CASE WHEN @rIsDisplayHSCResultDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayHSCResultDetail,
		   (CASE WHEN @rIsDisplayJeeDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayJeeDetail,
		   (CASE WHEN @rIsDisplayDiplomaDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayDiplomaDetail,
		   (CASE WHEN @rIsDisplayClassTeacherDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayClassTeacherDetail,
		   (CASE WHEN @rIsDisplayAdmissionDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayAdmissionDetail,
		   @rOrgId AS OrgId
		  
	 
    RETURN  
    
END
GO
PRINT N'Altering Procedure [sCertificate].[pRptFirstTrialCertificateGet]...';


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

DECLARE @lIsDisplayImageHeader bit = 0

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

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

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 179 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF(@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF(@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	--add for 28093 mantis start
	DECLARE @lIsShowPhoto bit = 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
	--add for 28093 mantis end

	SELECT
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			FT.Id,
			FT.Number,
			FT.AcademicId,
			FT.FirstTrialDate,
			FT.ExamCentre,
			FT.ExamYear,
			FT.SeatNo,
			FT.Trial,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			SM.LastName as Surname,
			SO.GenderId,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SM.StatusId,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			CM.DisplayTitle  AS ClassName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			(CASE WHEN CGM.Title='10' THEN  'SSC'
			WHEN  CGM.Title='12'  THEN 'HSC'  ElSE CGM.Title + ' '+'std'
			 END) AS Exam,
			 FT.Remark AS Remark,
			 ISNULL(SF.FatherName,'') As FatherName,
			 ISNULL(SF.MotherName,'') As MotherName,
			 SA.AdmissionDate,
			 SO.BirthDateInWord ,
			 SO.DateOfBirth,
			 SI.StudentPhoto,
			 @lIDConfigValue AS ItemValue,
			 SM.SUID ,
			 STM.Title as StreamName,
			 ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			 OM.ReportOrgTitle,
			--(CASE WHEN OI.CertificateHeaderA4Portrait IS NULL THEN
			--OI.CertificateHeaderA4
			--ELSE OI.CertificateHeaderA4Portrait END ) AS CertificateHeader
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			BM.Title AS Batch,
			ISNULL(SA.LeftDate,'') AS LeftDate,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(OM.PrincipalSignature,0x) AS PrincipalSignature,
			EI.EmployeeId,
			SC.PresentStreetOne AS PresentStreetOne,		--add for 28093 mantis start
			SC.PresentStreetTwo AS PresentStreetTwo,
			SC.PresentStreetThree AS PresentStreetThree,
			SC.PresentCountry AS PresentCountry,
			SC.PresentState AS PresentState,
			SC.PresentCity AS PresentCity,
			SC.PresentZipCode AS PresentZipCode,
			SC.PresentContactNo AS PresentContactNo,
			@lIsShowPhoto AS IsShowPhoto,
			CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
			ISNULL(SI.QRCode,'') AS QRCode,					--add for 28093 mantis end
			ISNULL(FT.LastExamName,'') AS LastExamName,   -- Mantis : 0027927 #Start
			ISNULL(FT.ObtainedMark,'') AS ObtainedMarkInLastExam,
			ISNULL(FT.AdditionalRemark,'') AS AdditionalRemark,
			DM.DisplayTitle AS DivisionName,
			BM.FromDate AS BatchStartDate,
			BM.ToDate AS BatchEndDate,
			ISNULL(SGM.Title,'') AS StudentGroup  -- #End

	FROM
			sCertificate.tFirstTrial FT
			INNER JOIN sStudent.tAcademic A ON FT.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN  sSetup.tStreamMaster STM ON STM.Id= CM.StreamId
			Left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sSetup.tClassGroupMaster CGM ON CGM.Id = CM.ClassGroupId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id			--add for 28093 mantis
			LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SM.StudentGroupId -- Mantis : 0027927
			
	WHERE
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			AND ((FT.FirstTrialDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((FT.FirstTrialDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((FT.Number=@rNumber) OR (@rNumber=''))
			AND ((FT.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((FT.Number <= @rToNo) OR (@rToNo=''))
			--Group By FT.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,FT.SeatNo,FT.Trial,SM.Code,SM.FirstName,OM.StateName,SO.GenderId,
			--OM.CityName,OM.StateName,FT.FirstTrialDate,FT.ExamCentre,FT.ExamYear,SM.MiddleName,SM.LastName,OM.CityName,SM.StatusId
			--,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering Procedure [sCertificate].[pFirstTrialAdd]...';


GO


ALTER PROCEDURE [sCertificate].[pFirstTrialAdd]
			
		@rId bigint
       ,@rAcademicId bigint
       ,@rNumber int
       ,@rFirstTrialDate date
       ,@rExamYear nvarchar(20)
       ,@rExamCentre nvarchar(100)
       ,@rSeatNo nvarchar(50)
       ,@rTrial nvarchar(20)
       ,@rCreatedUserId bigint
       ,@rOrgId int
       ,@rRemark nvarchar(200)
       ,@rBatchId int
       ,@rIsNumberBatchWise bit = 0
	   ,@rLastExamName nvarchar(150) = '' -- Mantis : 0027927 #Start
	   ,@rObtainedMark nvarchar(100) = ''
	   ,@rAdditionalRemark nvarchar(max) = '' -- #End

           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
	If(@rIsNumberBatchWise = 1)
	BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) FROM sCertificate.tFirstTrial WHERE OrgId=@rOrgId AND BatchId = @rBatchId
			SET @rNumber = @rNumber + 1
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tFirstTrial WHERE AcademicId=@rAcademicId AND BatchId = @rBatchId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tFirstTrial WHERE Number=@rNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	 END
	 ELSE
	 BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) FROM sCertificate.tFirstTrial WHERE OrgId=@rOrgId AND BatchId = @rBatchId
			SET @rNumber = @rNumber + 1
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tFirstTrial WHERE AcademicId=@rAcademicId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tFirstTrial WHERE Number=@rNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	  END
	 
	  DECLARE @lNextNumber BIGINT
	  BEGIN TRY
	BEGIN TRANSACTION
	  IF(@rId = 0)	
		BEGIN
			
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tFirstTrial', 0, 1, 1,@outNextNumber = @lNextNumber output
			
			INSERT INTO sCertificate.tFirstTrial
			(
				Id
			   ,AcademicId
			   ,Number
			   ,FirstTrialDate
			   ,ExamYear
			   ,ExamCentre
			   ,SeatNo
			   ,Trial
			   ,OrgId
			   ,CreatedUserId
			   ,CreatedDateTime
			   ,Remark
			   ,BatchId
			   ,LastExamName -- Mantis : 0027927 #Start
			   ,ObtainedMark
			   ,AdditionalRemark -- #End
			)
			VALUES
			(	@lNextNumber
			   ,@rAcademicId
			   ,@rNumber
			   ,@rFirstTrialDate
			   ,@rExamYear
			   ,@rExamCentre
			   ,@rSeatNo
			   ,@rTrial
			   ,@rOrgId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rRemark 
			   ,@rBatchId
			   ,@rLastExamName  -- Mantis : 0027927 #Start
			   ,@rObtainedMark
			   ,@rAdditionalRemark  -- #End
			)		
			SELECT @lNextNumber AS Result
		END
		
		ELSE
		 BEGIN
		 IF  EXISTS(SELECT Id FROM sCertificate.tFirstTrial WHERE AcademicId=@rAcademicId AND Id<>@rId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END
		 SET @lNextNumber = @rId
			UPDATE  sCertificate.tFirstTrial
			SET
				AcademicId=@rAcademicId,
				FirstTrialDate=@rFirstTrialDate,
				ExamYear=@rExamYear,
				ExamCentre=@rExamCentre,
				SeatNo=@rSeatNo,
				Trial=@rTrial,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate(),
				Remark=@rRemark,
				BatchId = @rBatchId,
				LastExamName = @rLastExamName, -- Mantis : 0027927 #Start
				ObtainedMark = @rObtainedMark,
				AdditionalRemark = @rAdditionalRemark -- #End
			  WHERE Id = @rId
			  SELECT @lNextNumber AS Result
		 END  	
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering Procedure [sCertificate].[pFirstTrialBulkGet]...';


GO

 
ALTER PROCEDURE [sCertificate].[pFirstTrialBulkGet]
	 
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.Code,			
			SA.Name,
			ISNULL(FT.Id,0) AS Id,
			ISNULL(FT.FirstTrialDate,'') AS FirstTrialDate,
			ISNULL(FT.Trial,'') AS Trial,
			ISNULL(FT.SeatNo,'') AS SeatNo,
			ISNULL(FT.ExamCentre,'') AS ExamCentre,
			ISNULL(FT.Remark,'') AS Remark,
			ISNULL(FT.LastExamName,'') AS LastExamName, -- Mantis : 0027927 #Start
			ISNULL(FT.ObtainedMark,'') AS ObtainedMark,
			ISNULL(FT.AdditionalRemark,'') AS AdditionalRemark -- #End
			
  FROM 
			[sStudent].[vStudentAcademic]  SA 
			LEFT JOIN sCertificate.tFirstTrial FT ON FT.AcademicId=SA.AcademicId
  WHERE 
			(SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SA.BatchId=@rBatchId
			AND SA.OrgID=@rOrgId order by SA.RollNo
END
GO
PRINT N'Altering Procedure [sCertificate].[pFirstTrialGet]...';


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

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
	
			FT.Id,
			FT.AcademicId,
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision,
			FT.Number,
			FT.FirstTrialDate,
			FT.ExamYear,
			FT.ExamCentre,
			FT.SeatNo,
			FT.Trial,
			FT.Remark,
			ISNULL(FT.LastExamName,'') AS LastExamName,   -- Mantis : 0027927 #Start
			ISNULL(FT.ObtainedMark,'') AS ObtainedMark,
			ISNULL(FT.AdditionalRemark,'') AS AdditionalRemark -- #End
  FROM 
            sCertificate.tFirstTrial FT
       INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=FT.AcademicId
			AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId
  WHERE 
  
      ((FT.Id = @rId) OR (@rId = 0))
     
      AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
      AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
       AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
    AND ((FT.FirstTrialDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((FT.FirstTrialDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((FT.Number >= @rFromNo) OR (@rFromNo=0))
	AND ((FT.Number <= @rToNo) OR (@rToNo = 0))
	
	ORDER BY FT.Number
END
GO
PRINT N'Altering Procedure [sCommunication].[pCircularGet]...';


GO
 
 
ALTER PROCEDURE [sCommunication].[pCircularGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rOrgGroupBatchId int,
	 @rIsSearch bit = 1,
	 @rAssigneeId tinyint,
	 @rCircularTypeId int,
	 @rCreatedUserId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			U.DisplayTitle as CreatedUserName,
			C.AssigneeId,
			AM.Title AS Assignee,
			CTM.Title AS CircularTypeTitle,
			CTM.HighlightColor,
			C.CircularTypeId,
			C.CreatedUserId,
			C.CreatedDateTime,
			ISNULL(C.StatusId,549) AS StatusId,
			ISNULL(C.PublishDateTime,'') as PublishDateTime,
			--CASE WHEN ISNULL(C.StatusId,549) =549 then 'Pending' WHEN C.StatusId=550 then 'Approve' ELSE 'Reject' END AS Status
			ISNULL(C.IsPublishInFuture,0) as PublishInFuture,
			ISNULL(C.IsConsent,0) AS IsConsent
  FROM 
            sCommunication.tCircular C
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=C.AssigneeId
            INNER JOIN sCommunication.tCircularTypeMaster CTM ON CTM.Id = C.CircularTypeId
  WHERE 
  
		((C.Id = @rId) OR (@rId = 0))
	AND ((C.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((C.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((C.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((C.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((C.AssigneeId IN (1,2,3) AND @rAssigneeId=1)  OR
		 (C.AssigneeId = @rAssigneeId AND @rAssigneeId IN (2,3)) OR
		  @rIsSearch = 0)
     AND (C.CircularTypeId=@rCircularTypeId OR @rIsSearch = 0)
    AND (C.CreatedUserId = @rCreatedUserId OR @rCreatedUserId = 0)
	ORDER BY C.StartDate DESC
END
GO
PRINT N'Altering Procedure [sCommunication].[pTempCircularAdd]...';


GO
 
ALTER PROCEDURE [sCommunication].[pTempCircularAdd]
	 
        @rId bigint,
		@rTitle nvarchar(200),
		@rRemark nvarchar(max),
		@rStartDate date,
		@rCreatedUserId bigint,
        @rOrgGroupId smallint,
        @rOrgGroupBatchId int,
        @rAssigneeId tinyint,
        @rCircularTypeId int,
        @rTempCircularId nvarchar(100),
		@rPublishDateTime DateTime = '',
		@rPublishInFuture bit = 0,
		@rIsConsent bit = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tCircular', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	 
	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsCircularBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 302 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsCircularBasedOnApproval = 0
	ELSE
	SET @lIsCircularBasedOnApproval = 1	
	
	Declare @StatusId smallint
	IF(@lIsCircularBasedOnApproval=0)
	SET @StatusId=550
	ELSE
	SET @StatusId=549
	
	INSERT INTO sCommunication.tCircular
		(
			Id,
			Title,
			Remark,
			StartDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			OrgGroupBatchId,
			AssigneeId,
			CircularTypeId,
			StatusId,
			PublishDateTime,
			IsPublishInFuture,
			IsConsent
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rStartDate,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rAssigneeId,
			@rCircularTypeId,
			@StatusId,
			@rPublishDateTime,
			@rPublishInFuture,
			@rIsConsent
		)
		
		SELECT @lNextNumber AS Result  
		    
		INSERT INTO sCommunication.tCircularScope
		SELECT @lNextNumber,SourceTypeId,SourceId,AssigneeToId
		FROM sCommunication.tTempCircularScope 
		WHERE TempCircularId = @rTempCircularId
		
		DELETE FROM sCommunication.tTempCircularScope WHERE TempCircularId = @rTempCircularId
		
		
	END	 

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


GO
ALTER PROCEDURE [sCommunication].[pDailyThoughtAssignAdd]
	 @rOrgId int,
	 @rMonth smallint,
	 @rXml nvarchar(MAX),
	 @rSourceId bigint = 0,
	 @rSourceTypeId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @StrXML XML  
    SET @StrXML = CAST(@rXml AS XML)  
   
	DECLARE @tDailyThoughtAssign TABLE  
	(  
		Id INT IDENTITY(1, 1),  
		Day SMALLINT,
		DailyThoughtId nvarchar(100),  
		IsSelect  SMALLINT
	)   
    INSERT INTO @tDailyThoughtAssign  
    SELECT           
            T.c.value('@Day','smallint') AS Day,  
            T.c.value('@DailyThoughtId','nvarchar(100)') AS DailyThoughtId,  
            T.c.value('@IsSelect','smallint') AS IsSelect             
    FROM   
            @StrXML.nodes('/Table/DailyThought')T(c)  

	Declare @lCount int=1
	WHILE(@lCount <= (SELECT count(*) FROM @tDailyThoughtAssign))                
	BEGIN
		DECLARE @lIsSelect SmallInt,@lDay SmallInt
		DECLARE @lDailyThoughtId nvarchar(100)

		SELECT @lIsSelect = IsSelect , @lDailyThoughtId = DailyThoughtId,@lDay = Day FROM @tDailyThoughtAssign WHERE Id = @lCount

		IF(@lIsSelect = 1)
		BEGIN
			--IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE DailyThoughtId = @lDailyThoughtId AND Month = @rMonth AND OrgId = @rOrgId AND Day <> @lDay)
			--BEGIN
			--	SELECT -101 AS Result

			--	COMMIT TRANSACTION
			--	RETURN
			--END
			IF NOT EXISTS(SELECT 1 FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](@lDailyThoughtId, ',')))
			BEGIN
				SELECT -102 AS Result

				COMMIT TRANSACTION
				RETURN
			END
			
			IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId)
			BEGIN
				UPDATE sCommunication.tDailyThoughtAssign
				SET
				DailyThoughtId = @lDailyThoughtId
				WHERE
				Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId
			END
			ELSE IF NOT EXISTS(SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId)
			BEGIN
				INSERT INTO sCommunication.tDailyThoughtAssign
				(
					DailyThoughtId,
					Day,
					Month,
					OrgId,
					SourceId,
					SourceTypeId	
				)
				VALUES
				(
					@lDailyThoughtId,
					@lDay,
					@rMonth,
					@rOrgId,
					@rSourceId,
					@rSourceTypeId
				)
			END
		END
		ELSE
		BEGIN
			IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE  Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId)
			BEGIN
				DELETE FROM sCommunication.tDailyThoughtAssign WHERE Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId
			END
		END
		SET @lCount = @lCount + 1
	END
		SELECT 1 AS RESULT
	COMMIT TRANSACTION

		END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
		SELECT ERROR_MESSAGE() as result
	END CATCH
END
GO
PRINT N'Altering Procedure [sCommunication].[pDailyThoughtGet]...';


GO
ALTER PROCEDURE [sCommunication].[pDailyThoughtGet]

	@rOrgId int,
	@rSourceId bigint = 0,
	@rSourceTypeId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @lDay smallint , @lMonth smallint
	DECLARE @lOrgGroupId Int
	DECLARE @lDailyThoughtId nvarchar(100)
	DECLARE @lFinalDailyThoughtId nvarchar(100) = ''

	SET @lDay = DAY(sCommon.fGetDate())
	SET @lMonth = MONTH(sCommon.fGetDate())
	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId

	IF(@rSourceTypeId = 2001)
	BEGIN
		DECLARE @lClassId int,@lDivisionId int,@lOrgId int

		SELECT @lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId
		 FROM sStudent.tAcademic A 
		 WHERE A.Id = @rSourceId  

		 IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2005 AND SourceId = @lDivisionId)
			BEGIN --Check If DailyThought Assign to particular day
				SELECT 
					DTM.Id,
					DTM.Number,
					DTM.Title,
					DTM.Remark,
					DTS.Title As [Subject]
				FROM
					sCommunication.tDailyThoughtAssign DTA
					INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
					INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
				WHERE
					DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND SourceTypeId = 2005 AND SourceId = @lDivisionId

				SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2005 AND SourceId = @lDivisionId
			END
		ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2016 AND SourceId = @lClassId)
			BEGIN --Check If DailyThought Assign to particular day
					SELECT 
						DTM.Id,
						DTM.Number,
						DTM.Title,
						DTM.Remark,
						DTS.Title As [Subject]
					FROM
						sCommunication.tDailyThoughtAssign DTA
						INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
						INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
					WHERE
						DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND SourceTypeId = 2016 AND SourceId = @lClassId

					SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2016 AND SourceId = @lClassId
				END
		ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND (SourceTypeId = 2021 AND SourceId = @lOrgId))
			BEGIN --Check If DailyThought Assign to particular day

					SELECT 
						DTM.Id,
						DTM.Number,
						DTM.Title,
						DTM.Remark,
						DTS.Title As [Subject]
					FROM
						sCommunication.tDailyThoughtAssign DTA
						INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
						INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
					WHERE
						DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND (SourceTypeId = 2021 AND SourceId = @lOrgId)

					SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND (SourceTypeId = 2021 AND SourceId = @lOrgId)
			END
	END
	
	IF(@rSourceTypeId = 95)
	BEGIN
			IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0)))
			BEGIN --Check If DailyThought Assign to particular day
				SELECT 
					DTM.Id,
					DTM.Number,
					DTM.Title,
					DTM.Remark,
					DTS.Title As [Subject]
				FROM
					sCommunication.tDailyThoughtAssign DTA
					INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
					INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
				WHERE
					DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0))

				SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0))

			END
	END
	 
	IF(@lFinalDailyThoughtId = '')
	BEGIN 
		IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0)))
			BEGIN --Check If DailyThought Assign to particular day
			     
				SELECT 
					DTM.Id,
					DTM.Number,
					DTM.Title,
					DTM.Remark,
					DTS.Title As [Subject]
				FROM
					sCommunication.tDailyThoughtAssign DTA
					INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
					INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
				WHERE
					DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0))

				SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0))

			END
		ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtTemp WHERE CONVERT(NVARCHAR,CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) AND OrgGroupId = @lOrgGroupId)
		BEGIN --If DailyThought loaded in temp table for particular day 
			SELECT 
				DTM.Id,
				DTM.Number,
				DTM.Title,
				DTM.Remark,
				DTS.Title As [Subject]
			FROM
				sCommunication.tDailyThoughtTemp DTM 
				INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = DTM.OrgGroupId
			WHERE
				OM.Id = @rOrgId
		END
		ELSE
		BEGIN --If DailyThought not Assign to particular day than insert into temp table and select from that
			DELETE FROM sCommunication.tDailyThoughtTemp WHERE OrgGroupId = @lOrgGroupId

			IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtMaster WHERE OrgGroupId = @lOrgGroupId AND IsObsolete = 0 AND IsRead = 0)
			BEGIN
				
				SELECT Top 1 @lDailyThoughtId = Id FROM sCommunication.tDailyThoughtMaster WHERE OrgGroupId = @lOrgGroupId AND IsObsolete = 0 AND IsRead = 0 ORDER BY CreatedDateTime ASC

				INSERT INTO sCommunication.tDailyThoughtTemp 
				  (
					Id,
					DailyThoughtSubjectId,
					Title,
					Remark,
					IsObsolete,
					Number,
					OrgGroupId,
					IsRead,
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime
				  )
				  SELECT
					Id,
					DailyThoughtSubjectId,
					Title,
					Remark,
					IsObsolete,
					Number,
					OrgGroupId,
					IsRead,
					CreatedUserId,
					sCommon.fGetDate(),
					UpdatedUserId,
					UpdatedDateTime
				  FROM 
					sCommunication.tDailyThoughtMaster
				  WHERE 
					Id = @lDailyThoughtId

				  UPDATE 
					sCommunication.tDailyThoughtMaster 
				  SET 
					IsRead = 1 
				  WHERE 
					Id = @lDailyThoughtId

				  SELECT 
					DTM.Id,
					DTM.Number,
					DTM.Title,
					DTM.Remark,
					DTS.Title As [Subject]	
				  FROM
					sCommunication.tDailyThoughtTemp DTM 
					INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
				  WHERE
					DTM.OrgGroupId = @lOrgGroupId
			END
			ELSE
			BEGIN --If All thought read than change flag IsRead to false in all thought and than assign in temp table
					UPDATE sCommunication.tDailyThoughtMaster SET IsRead = 0 WHERE OrgGroupId = @lOrgGroupId
					
					IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtMaster WHERE OrgGroupId = @lOrgGroupId AND IsObsolete = 0 AND IsRead = 0)
					BEGIN
						
						SELECT Top 1 @lDailyThoughtId =(Id) FROM sCommunication.tDailyThoughtMaster WHERE OrgGroupId = @lOrgGroupId AND IsObsolete = 0 AND IsRead = 0 ORDER By CreatedDateTime ASC
				
						INSERT INTO sCommunication.tDailyThoughtTemp 
						  (
							Id,
							DailyThoughtSubjectId,
							Title,
							Remark,
							IsObsolete,
							Number,
							OrgGroupId,
							IsRead,
							CreatedUserId,
							CreatedDateTime,
							UpdatedUserId,
							UpdatedDateTime
						  )
						  SELECT
							Id,
							DailyThoughtSubjectId,
							Title,
							Remark,
							IsObsolete,
							Number,
							OrgGroupId,
							IsRead,
							CreatedUserId,
							sCommon.fGetDate(),
							UpdatedUserId,
							UpdatedDateTime
						  FROM 
							sCommunication.tDailyThoughtMaster
						  WHERE 
							Id = @lDailyThoughtId

						  UPDATE 
							sCommunication.tDailyThoughtMaster 
						  SET 
							IsRead = 1 
						  WHERE 
							Id IN (@lDailyThoughtId)

						  SELECT 
							DTM.Id,
							DTM.Number,
							DTM.Title,
							DTM.Remark,
							DTS.Title As [Subject]
						  FROM
							sCommunication.tDailyThoughtTemp DTM 
							INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
						  WHERE
							DTM.OrgGroupId = @lOrgGroupId
					END
			END
		END
	END
END
GO
PRINT N'Altering Procedure [sEMeeting].[pMeetingTypeGet]...';


GO

ALTER PROCEDURE [sEMeeting].[pMeetingTypeGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			Select OM.AutoId as Id, 
			OM.Title
			from sEMeeting.tMeetingTypeMaster OM 
			where IsObsolete = 0
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Altering Procedure [sEMeeting].[pMeetingTypeMasterAdd]...';


GO

ALTER PROCEDURE [sEMeeting].[pMeetingTypeMasterAdd]
	@rAutoId smallint,
	@rTitle nvarchar(100),
	@rOrgGroupId smallint,
	@rIsObsolete bit = 0,
	@rCreatedUserId bigint,
	@rCode nvarchar(10),
	@rOrderIndex int = 0,
	@rDescription nvarchar(max) 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY

	BEGIN TRANSACTION	

	BEGIN

	IF (@rAutoId = 0)
	BEGIN
	 
	IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where Title = @rTitle)
		BEGIN
			SELECT -101 as Result
		END
	ELSE
	    BEGIN
			INSERT INTO sEMeeting.tMeetingTypeMaster
			(
				Title,
				OrgGroupId,
				IsObsolete,
				CreatedUserId,
				CreatedDateTime,
				Code,
				OrderIndex,
				Description
			)
			VALUES
			(
				@rTitle,
				@rOrgGroupId,
				@rIsObsolete,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCode,
				@rOrderIndex,
				@rDescription
			)
				SELECT 1 AS Result
		END
	END
	ELSE
	BEGIN 
		Update sEMeeting.tMeetingTypeMaster
		SET 
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = GETUTCDATE(),
			OrderIndex = @rOrderIndex,
			Code = @rCode,
			Description = @rDescription
		WHERE AutoId = @rAutoId
		SELECT 11 AS Result
	END
	END

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


GO
 
ALTER PROCEDURE [sEMeeting].[pOnlineMeetingGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rFromDate date = '',
	 @rToDate date = '',
	 @rEmployeeId bigint = 0,
	 @rMeetingTypeId smallint = 0,
	 @rIsCompleted int = 0,
	 @rAssigneeId tinyint,
	 @rUserId bigint = 0,
	 @rOnlineMeetingAccountId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	if(@rId = 0)
	BEGIN 
	SELECT 
			OM.Id,
			EM.FirstName +' '+ EM.LastName as Teacher,
			DM.Title as MeetingType,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			OM.IsCompleted as StatusId,
		    ISNULL(OM.Title,'') as Title,
			OM.StartDate AS TeacherStartDate,
			OM.EndDate AS TeacherEndDate,
			OM.AssigneeId,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sSetup.tClassMaster CM ON OMS.ScopeSourceId = CM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sSetup.tDivisionMaster DM ON OMS.ScopeSourceId = DM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2005
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as Assignee 
	  FROM 
			sEMeeting.tOnlineMeeting OM
			
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId AND DM.DataTypeId = 3
			INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=OM.AssigneeId
	  WHERE 
  
				((OM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((OM.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OM.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OM.HostEmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
			AND ((OM.MeetingTypeId = @rMeetingTypeId) OR (@rMeetingTypeId = 0))
			AND ((CONVERT(int,OM.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = 0))
			AND (OM.AssigneeId IN (1,2,3) AND @rAssigneeId=1)  OR
			(OM.AssigneeId = @rAssigneeId AND @rAssigneeId IN (2,3))
			AND OM.IsCompleted <> 551			
			ORDER BY
			
			OM.StartDate , OM.StartTime asc
	SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2021

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2017

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN  sSetup.tClassMaster CM
				ON OMS.ScopeSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2016

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
				WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2005

			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		    INNER JOIN sStudent.tStudentMaster SM
				ON OMS.ScopeSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2001
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS ROllNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON OMS.ScopeSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=95
	SELECT
		OnlineMeetingId, 
		ReferencePath 
		from sEMeeting.tOnlineMeetingReference OMR
		where OMR.OnlineMeetingId = @rId
	END
	ELSE
	BEGIN
		SELECT 
			OM.Id,
			EM.EmployeeName as Teacher,
			Em.EmployeeId as TeacherId,
			DM.Title as MeetingType,
			DM.Id as MeetingTypeId,
			CONVERT(NVARCHAR,OM.StartDate) as StartDate,
			CONVERT(NVARCHAR,OM.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OM.EndDate) as EndDate,
			CONVERT(NVARCHAR,OM.EndTime,108) as EndTime,
			OM.IsCompleted as StatusId,
			OM.Title as MeetingTitle,
			OM.Description,
			OM.IsDisplayMeetingId,
			OM.MeetingId,
			OM.MeetingPassword,
			ISNULL(OM.IsReference,0) as IsReference,
			ISNULL(OM.IsResource,0) as IsResource,
			ISNULL(OM.IsCompleted,0) as IsCompleted,
			ISNULL(OM.IsMeetingStarted,0) as IsMeetingStarted,
			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(OM.MeetingAccountId,0) AS MeetingAccountId,
			ISNULL(OM.IsMeetingCreated,0) AS IsMeetingCreated,
			ISNULL(OM.IsTrackAttendance,0) AS IsTrackAttendance,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			OM.AssigneeId,
			OM.StartDate AS TeacherStartDate,
			OM.EndDate AS TeacherEndDate
	  FROM 
			sEMeeting.tOnlineMeeting OM
			
			INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OM.HostEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId AND DM.DataTypeId = 3
			LEFT JOIN sEMeeting.tOnlineMeetingSettings OMS ON OMS.OnlineMeetingId = OM.Id
			INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=OM.AssigneeId
	  WHERE 
			(OM.Id = @rId) AND OM.IsCompleted <> 551
	  ORDER BY
			OM.StartDate , OM.StartTime asc
		SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2021

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2017

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN  sSetup.tClassMaster CM
				ON OMS.ScopeSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
				LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2016

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id	
				LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
				WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2005

			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		    INNER JOIN sStudent.tStudentMaster SM
				ON OMS.ScopeSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
				LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
				LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2001
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS ROllNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON OMS.ScopeSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=95
		SELECT
		OnlineMeetingId, 
		ReferencePath 
		from sEMeeting.tOnlineMeetingReference OMR
		where OMR.OnlineMeetingId = @rId
	END
END TRY
BEGIN CATCH 
		SELECT -1 AS Result
END CATCH
END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingAdd]...';


GO
 
CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAdd]
	 
        @rId bigint = 0,
		@rOrgGroupId smallint,
		@rMeetingTypeId smallint,
		@rHostEmployeeId bigint,
		@rStartDate datetime,
		@rStartTime datetime,
		@rEndDate datetime,
		@rEndTime datetime,
		@rTitle nvarchar(100) = '',
		@rDescription nvarchar(max) = '',
		@rIsDisplayMeetingId bit = 0,
		@rMeetingId nvarchar(50) = '',
		@rMeetingPass nvarchar(50) = '',
		@rIsReference bit = 0,
		@rIsResource bit=0,
		@rIsCompleted bit = 0,
		@rIsMeetingStarted bit = 0,
		@rMeetingAccountId int = 0,
		@rIsMeetingCreated bit=0,
		@rIsObsolete bit = 0,
		@rCreatedUserId bigint,
		@rIsOnParticipantVideo bit = 0,
		@rIsOnParticipantAudio bit = 0,
		@rIsOnHostVideo bit = 0,
		@rIsOnHostAudio bit = 0,
		@rIsOnParticipantScreenShare bit = 0,
		@rIsOnHostscreenShare bit = 0,
		@rAssigneeId tinyint,
		@rIsTrackAttendance bit = 0,
		@rOnlineMeetingScopeList sEMeeting.OnlineMeetingScopeDetailType READONLY,
		@rOnlineMeetingReferenceList sEMeeting.OnlineMeetingReferenceDetailType READONLY
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	 DECLARE @lAccountEmailId NVARCHAR(200),@lAccountPassword NVARCHAR(200),@lAPIKey NVARCHAR(100),@lAPISecret NVARCHAR(100),@lWebAPIKey NVARCHAR(100),
	         @lWebAPISecret NVARCHAR(100),@lMeetingProviderId NVARCHAR(100),@lJWTToken NVARCHAR(MAX),@lOAuthAccountId NVARCHAR(MAX), @lOAuthClientId NVARCHAR(MAX),@lOAuthClientSecret NVARCHAR(MAX)

	SELECT @lAccountEmailId = AccountEmailId,@lAccountPassword = AccountPassword,@lAPIKey = APIKey,@lAPISecret = APISecret,@lWebAPIKey = WebAPIKey,@lWebAPISecret = WebAPISecret,@lMeetingProviderId = MeetingProviderId,
	@lJWTToken = JWTToken, @lOAuthAccountId = OAuthAccountId , @lOAuthClientId = OAuthClientId , @lOAuthClientSecret = OAuthClientSecret
	    FROM sAcademic.tOnlineMeetingAccount
		WHERE Id = @rMeetingAccountId

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEMeeting.tOnlineMeeting', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	INSERT INTO sEMeeting.tOnlineMeeting
		(
			Id,
			OrgGroupId,
			MeetingTypeId,
			HostEmployeeId,
			StartDate,
			StartTime,
			EndDate,
			EndTime,
			Title,
			Description,
			IsDisplayMeetingId,
			MeetingId,
			MeetingPassword,
			IsReference,
			IsResource,
			IsCompleted,
			IsMeetingStarted,
			MeetingAccountId,
			IsMeetingCreated,
			IsObsolete,
			AssigneeId,
			IsTrackAttendance,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rOrgGroupId,
			@rMeetingTypeId,
			@rHostEmployeeId,
			@rStartDate,
			@rStartTime,
			@rEndDate, 
			@rEndTime,
			@rTitle,
			@rDescription,
			@rIsDisplayMeetingId,
			@rMeetingId,
			@rMeetingPass,
			@rIsReference,
			@rIsResource,
			@rIsCompleted,
			@rIsMeetingStarted,
			@rMeetingAccountId,
			@rIsMeetingCreated,
			@rIsObsolete,
			@rAssigneeId,
			@rIsTrackAttendance,
			@rCreatedUserId,
			GetUtcDate()
		)
		    
	INSERT INTO sEMeeting.tOnlineMeetingScope
			(
			OnlineMeetingId,
			ScopeSourceTypeId,
			ScopeSourceId,
			IsObsolete,
			AssigneeId,
			CreatedUserId,
			CreatedDateTime
			)
			SELECT 
			@lNextNumber,
			ScopeSourceTypeId,
			ScopeSourceId,
			@rIsObsolete,
			@rAssigneeId,
			@rCreatedUserId,
			GetUtcDate()
			from @rOnlineMeetingScopeList

	IF (@rIsReference = 'true')
	BEGIN
	INSERT INTO sEMeeting.tOnlineMeetingReference
	(
	OnlineMeetingId,
	ReferencePath
	)
	SELECT
	@lNextNumber,
	ReferencePath
	from @rOnlineMeetingReferenceList
		
	END

	IF(@rMeetingTypeId = 2)
		BEGIN
		INSERT INTO sEMeeting.tOnlineMeetingSettings
		(
			OnlineMeetingId,
			IsOnParticipantVideo,
			IsOnParticipantAudio,
			IsOnHostVideo,
			IsOnHostAudio,
			IsOnParticipantScreenShare,
			IsOnHostscreenShare,
			AccountEmailId,
			AccountPassword,
			APIKey,
			APISecret,
			WebAPIKey,
			WebAPISecret,
			MeetingProviderId,
			JWTToken,
			OAuthAccountId,
			OAuthClientId,
			OAuthClientSecret
		)
		VALUES
		(
			@lNextNumber,
			@rIsOnParticipantVideo,
			@rIsOnParticipantAudio,
			@rIsOnHostVideo,
			@rIsOnHostAudio,
			@rIsOnParticipantScreenShare,
			@rIsOnHostscreenShare,
			@lAccountEmailId,
			@lAccountPassword,
			@lAPIKey,
			@lAPISecret,
			@lWebAPIKey,
			@lWebAPISecret,
			@lMeetingProviderId,
			@lJWTToken,
			@lOAuthAccountId,
			@lOAuthClientId,
			@lOAuthClientSecret
		)
		END
		
	SELECT @lNextNumber as Result
	END	 

ELSE
	 BEGIN
	    UPDATE sEMeeting.tOnlineMeeting
	    SET
		   OrgGroupId = @rOrgGroupId,
		   MeetingTypeId = @rMeetingTypeId,
		   HostEmployeeId = @rHostEmployeeId,
		   StartDate = @rStartDate,
		   StartTime = @rStartTime,
		   EndDate = @rEndDate,
		   EndTime = @rEndTime,
		   Title = @rTitle,
		   Description = @rDescription,
		   IsDisplayMeetingId = @rIsDisplayMeetingId,
		   MeetingId = @rMeetingId,
		   MeetingPassword = @rMeetingPass,
		   IsReference = @rIsReference,
		   IsResource = @rIsResource,
		   IsCompleted = @rIsCompleted,
		   IsMeetingStarted = @rIsMeetingStarted,
		   MeetingAccountId = @rMeetingAccountId,
		   IsMeetingCreated = @rIsMeetingCreated,
		   IsObsolete = @rIsObsolete,
		   UpdatedUserId = @rCreatedUserId,
		   UpdatedDateTime = GetUtcDate()

	      WHERE Id = @rId
		  
		delete from sEMeeting.tOnlineMeetingScope where OnlineMeetingId = @rId

		INSERT INTO sEMeeting.tOnlineMeetingScope
			(
			OnlineMeetingId,
			ScopeSourceTypeId,
			ScopeSourceId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
			)
			SELECT 
			@rId,
			ScopeSourceTypeId,
			ScopeSourceId,
			@rIsObsolete,
			@rCreatedUserId,
			GetUtcDate()
			from @rOnlineMeetingScopeList
		
		delete from sEMeeting.tOnlineMeetingReference where OnlineMeetingId = @rId

		IF (@rIsReference = 'true')
		BEGIN
			INSERT INTO sEMeeting.tOnlineMeetingReference
			(
			OnlineMeetingId,
			ReferencePath
			)
			SELECT
			@rId,
			ReferencePath
			from @rOnlineMeetingReferenceList
		END

	    SELECT 11 AS Result
	
	 END  	

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


GO

 
ALTER PROCEDURE [sEMeeting].[pOnlineMeetingTeacherStudentListGet]
	 @rId bigint = 0,	 
	 @rScopeSourceId bigint,
	 @rScopeSourceTypeId int,
	 @rMeetingTypeId int = 0,
	 @rStartDate date = '',
	 @rEndDate date = '',
	 @rIsCompleted int= 0,
	 @rTitle nvarchar(100) ='',
	 @rOrgGroupBatchId int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	if (@rId = 0)
		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 = @rScopeSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId

	 If (@rScopeSourceTypeId = 2003)
	 BEGIN
	
	  SELECT 
			OM.Id,
			DM.Title AS MeetingType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') AS Teacher,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			(CASE WHEN OM.IsCompleted=0 THEN 'Pending' WHEN OM.IsCompleted=1 THEN 'Completed'  WHEN OM.IsCompleted=721 THEN 'Cancel' END) AS Status,
			ISNULL(OM.Title,'') AS Title
			
		FROM 
				sEMeeting.tOnlineMeeting OM
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId 
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId AND DM.DataTypeId = 3
				INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON OMS.OnlineMeetingId = OM.Id
				INNER JOIN (SELECT OMS.OnlineMeetingId FROM sEMeeting.tOnlineMeetingScope OMS
				WHERE (
				( 
				(OMS.ScopeSourceTypeId = 2021 AND OMS.ScopeSourceId =@lOrgId) 
				OR
				(OMS.ScopeSourceTypeId = 2017 AND OMS.ScopeSourceId =@lDepartmentId) OR
				(OMS.ScopeSourceTypeId = 2016 AND OMS.ScopeSourceId =@lClassId) OR
				(OMS.ScopeSourceTypeId = 2005 AND OMS.ScopeSourceId =@lDivisionId) OR
				(OMS.ScopeSourceTypeId = 2003 AND OMS.ScopeSourceId =@lStudentId) OR
				(OMS.ScopeSourceTypeId = 2001 AND OMS.ScopeSourceId =@lAcademicId)
				 ))
				) D
				ON D.OnlineMeetingId= OM.Id

			WHERE
				((OM.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				AND ((OM.EndDate >= CASE WHEN OM.MeetingTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '1900-01-01' END)) 
				AND ((OM.StartDate <= CASE WHEN OM.MeetingTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '9999-01-01' END))
				AND ((OM.StartTime <= CASE WHEN OM.MeetingTypeId = 1 AND OM.StartDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OM.StartTime END)) 
				AND ((OM.EndTime >= CASE WHEN OM.MeetingTypeId = 1  AND OM.EndDate = CONVERT(varchar,GETDATE(),23)THEN CONVERT(varchar,GETDATE(),14) ELSE OM.EndTime END))
				AND ((OM.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
				AND ((OM.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
				AND ((OM.MeetingTypeId = @rMeetingTypeId)OR (ISNULL(@rMeetingTypeId,0)=0))
				AND ((Convert(int,OM.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = 0))
				AND OM.IsCompleted <> 551
				
				ORDER BY OM.IsCompleted,OM.StartDate,OM.StartTime,OM.EndDate
			END
		
	IF (@rScopeSourceTypeId = 95)
	BEGIN 
		SELECT 
			OM.Id,
			DM.Title AS MeetingType,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			(CASE WHEN OM.IsCompleted=0 THEN 'Pending' WHEN OM.IsCompleted=1 THEN 'Completed'  WHEN OM.IsCompleted=721 THEN 'Cancel' END) AS Status,
			ISNULL(OM.Title,'') As Title,
			OM.StartDate AS TeacherStartDateTime,
			OM.EndDate AS TeacherEndDateTime
			FROM 
				sEMeeting.tOnlineMeeting OM
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId AND DM.DataTypeId = 3
				INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON OMS.OnlineMeetingId = OM.Id
			WHERE
				((OM.MeetingTypeId = @rMeetingTypeId) OR (@rMeetingTypeId = 0))
				AND ((OM.EndDate >= CASE WHEN OM.MeetingTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '1900-01-01' END)) 
				AND ((OM.StartDate <= CASE WHEN OM.MeetingTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '9999-01-01' END))
				AND ((OM.StartTime <= CASE WHEN OM.MeetingTypeId = 1 AND OM.StartDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OM.StartTime END)) 
				AND ((OM.EndTime >= CASE WHEN OM.MeetingTypeId = 1 AND OM.EndDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OM.EndTime END))
				AND ((OM.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
				AND ((OM.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
				AND (OM.HostEmployeeId = @rScopeSourceId OR OMS.ScopeSourceId = @rScopeSourceId AND OMS.ScopeSourceTypeId = @rScopeSourceTypeId)
				AND ((Convert(int,OM.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = 0))
				AND ((OM.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				AND OM.IsCompleted <> 551
				ORDER BY OM.IsCompleted,OM.StartDate,OM.StartTime,OM.EndDate
		END
		END
	ELSE
	IF (@rScopeSourceTypeId = 2003)
	BEGIN 

	 DECLARE @lAcademicId2 bigint,@lStudentId2 bigint,@lClassId2 int,@lDivisionId2 int,@lOrgId2 int,@lDepartmentId2 int,@lEmployeeId2 bigint,
	 @lClassName2 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 = @rScopeSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId



	SELECT
			OM.Id,
			DM.Title AS MeetingType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'')  AS Teacher,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndTime,
			(CASE WHEN OM.IsCompleted=0 THEN 'Pending' ELSE 'Completed' END) AS Status,
			OM.MeetingTypeId AS MeetingTypeId,
			OM.IsDisplayMeetingId AS IsDisplayMeetingId,
			OM.MeetingId AS MeetingId,
			OM.MeetingPassword AS MeetingPassword,
			ISNULL(OM.IsMeetingStarted,'') AS IsMeetingStarted,
			OM.IsCompleted AS IsCompleted,
			ISNULL(OM.Description,'')AS Description,
			ISNULL(OM.Title,'') AS Title,
			ISNULL(OM.IsMeetingStarted,'') AS IsMeetingStarted,
			OM.IsMeetingCreated AS IsMeetingCreated,
			OM.IsReference,
			OM.IsResource
          FROM 
				sEMeeting.tOnlineMeeting OM
				
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId 
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId AND DM.DataTypeId = 3
				INNER JOIN (SELECT OMS.OnlineMeetingId FROM sEMeeting.tOnlineMeetingScope OMS
				WHERE (
				( 
				(OMS.ScopeSourceTypeId = 2021 AND OMS.ScopeSourceId =@lOrgId) 
				OR
				(OMS.ScopeSourceTypeId = 2017 AND OMS.ScopeSourceId =@lDepartmentId2) OR
				(OMS.ScopeSourceTypeId = 2016 AND OMS.ScopeSourceId =@lClassId2) OR
				(OMS.ScopeSourceTypeId = 2005 AND OMS.ScopeSourceId =@lDivisionId2) OR
				(OMS.ScopeSourceTypeId = 2003 AND OMS.ScopeSourceId =@lStudentId2) OR
				(OMS.ScopeSourceTypeId = 2001 AND OMS.ScopeSourceId =@lAcademicId2)
				 ))
				) D
				ON D.OnlineMeetingId= OM.Id

            
            WHERE
				 OM.Id = @rId

				ORDER BY OM.IsCompleted,OM.StartDate,OM.EndDate
		END
		
		IF(@rScopeSourceTypeId = 95)
		BEGIN
		SELECT 
			OM.Id,
			DM.Title AS MeetingType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'')  AS Teacher,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndTime,
			(CASE WHEN OM.IsCompleted=0 THEN 'Pending' ELSE 'Completed' END) AS Status,
			OM.MeetingTypeId AS MeetingTypeId,
			OM.IsDisplayMeetingId AS IsDisplayMeetingId,
			OM.MeetingId AS MeetingId,
			OM.MeetingPassword AS MeetingPassword,
			OM.IsCompleted AS IsCompleted,
			ISNULL(OM.Title,'') AS Title,
			ISNULL(OM.Description,'')AS Description,
			ISNULL(OM.IsMeetingStarted,'') AS IsMeetingStarted,
			OM.IsMeetingCreated AS IsMeetingCreated,
			OM.IsTrackAttendance AS IsTrackAttendance,
			OM.IsReference,
			OM.IsResource,
			OM.HostEmployeeId
		FROM 
				sEMeeting.tOnlineMeeting OM
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId AND DM.DataTypeId = 3
				INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON OMS.OnlineMeetingId = OM.Id
		WHERE
			 OM.Id = @rId
			 AND (OM.HostEmployeeId = @rScopeSourceId OR OMS.ScopeSourceId = @rScopeSourceId AND OMS.ScopeSourceTypeId = @rScopeSourceTypeId)
			ORDER BY OM.CreatedDateTime
		SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2021

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId 
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2017

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN  sSetup.tClassMaster CM
				ON OMS.ScopeSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2016

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId	
				WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2005

			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		    INNER JOIN sStudent.tStudentMaster SM
				ON OMS.ScopeSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId	
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2001
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS ROllNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON OMS.ScopeSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=95

		SELECT
		OnlineMeetingId, 
		ReferencePath 
		from sEMeeting.tOnlineMeetingReference OMR
		where OMR.OnlineMeetingId = @rId
			END
		
END
GO
PRINT N'Altering Procedure [sPurchase].[pGoodsReceivedNoteGet]...';


GO


ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  GRN.Id,
				GRN.GRNNumber                               ,
				GRN.OrgGroupId,
				GRN.LocationId,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.VendorId,
				GRN.RequestedBy,
				GRN.BillToAddress,
				GRN.StatusId,
				GRN.PODueDate,
				ISNULL(SM.Title,'') as Status,
				VM.Title AS VendorName 
		from   [sPurchase].[tGoodsReceivedNote] GRN(nolock) 
			   Left JOIN sProcurement.tVendorMaster  VM on GRN.VendorId = VM.ID
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = GRN.StatusId
		where  GRN.Id=@rId AND GRN.IsObsolete = 0

		select GRND.Id,
			   GRND.GoodsReceivedNoteId,
			   GRND.PurchaseRequestDetailId,
			   GRND.OrgGroupId,
			   GRND.UnitTypeId,
			   GRND.CategoryId,
			   GRND.SubCategoryId,
			   GRND.StockItemId,
			   GRND.POQty,
			   GRND.ReceivedQty,
			   GRND.PreviousGRNQty,
			   GRND.UnitPrice,
			   GRND.Remark, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tGoodsReceivedNoteDetail] GRND (nolock)
			   Inner JOIN	sPurchase.tGoodsReceivedNote GRN	ON GRN.Id = GRND.GoodsReceivedNoteId AND GRN.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  GRND.GoodsReceivedNoteId=@rId

		select  AutoId,
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl
		from    sPurchase.tDocumentManagement
		where   SourceId = @rId and SourceTypeId = 2043
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pGoodsReceivedNoteSearchGet]...';


GO


ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				GRN.Id,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.VendorId,
				GRN.GRNNumber as Number,
				GRN.RequestedBy, 
				GRN.LocationId, 
				GRN.PODueDate,
				ISNULL(SM.Title,'') as Status,
				VM.Code AS VendorCode,
			    VM.Title AS VendorName,
				PR.Number as PurchaseNumber,
				PO.RefNumber as PurchaseOrderNumber
		FROM		
				sPurchase.tGoodsReceivedNote GRN (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on GRN.StatusId = SM.Id
				Left JOIN sProcurement.tVendorMaster  VM on GRN.VendorId = VM.ID
				Left Join [sPurchase].[tPurchaseRequest] PR on PR.Id = GRN.PurchaseRequestId
				Left Join [sPurchase].[tPurchaseOrder] PO on PO.Id = GRN.PurchaseOrderId
		WHERE 
				((GRN.GRNNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((GRN.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND GRN.IsObsolete = 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pGoodsReceivedNoteSRGet]...';


GO


ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSRGet]
	  @rId int,
	  @rQualityCheckId bigint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  GRN.Id,
				GRN.GRNNumber                               ,
				GRN.OrgGroupId,
				GRN.LocationId,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.VendorId,
				GRN.RequestedBy,
				GRN.BillToAddress,
				GRN.StatusId,
				GRN.PODueDate,
				ISNULL(SM.Title,'') as Status,
				VM.Title AS VendorName 
		from   [sPurchase].[tGoodsReceivedNote] GRN(nolock) 
			   INNER JOIN sPurchase.tQualityCheck QC on QC.GoodsReceivedNoteId = GRN.Id AND QC.Id = @rQualityCheckId
			   LEFT JOIN  sProcurement.tVendorMaster  VM on GRN.VendorId = VM.ID
			   LEFT Join  sWf.tWfStatusMaster SM ON SM.Id = GRN.StatusId
		where  GRN.Id=@rId AND GRN.IsObsolete = 0

		select GRND.Id,
			   GRND.GoodsReceivedNoteId,
			   GRND.PurchaseRequestDetailId,
			   GRND.OrgGroupId,
			   GRND.UnitTypeId,
			   GRND.CategoryId,
			   GRND.SubCategoryId,
			   GRND.StockItemId,
			   GRND.POQty,
			   GRND.ReceivedQty,
			   GRND.PreviousGRNQty,
			   GRND.UnitPrice,
			   GRND.Remark, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tGoodsReceivedNoteDetail] GRND (nolock)
			   INNER JOIN	sPurchase.tGoodsReceivedNote GRN	ON GRN.Id = GRND.GoodsReceivedNoteId AND GRN.IsObsolete = 0
			   INNER JOIN sPurchase.tQualityCheck QC on QC.GoodsReceivedNoteId = GRN.Id AND QC.Id = @rQualityCheckId
			   INNER JOIN   sPurchase.tQualityCheckDetail QCD on QCD.QualityCheckId = QC.Id
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId 
			   INNER JOIN   sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  GRND.GoodsReceivedNoteId=@rId AND QCD.RejectedQty > 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pInvoiceGenerateGet]...';


GO


ALTER PROCEDURE [sPurchase].[pInvoiceGenerateGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  IG.Id,
				IG.INVNumber,
				IG.OrgGroupId,
				IG.LocationId,
				IG.GoodsReceivedNoteId,
				IG.RequestedBy,
				IG.VendorId,
				IG.InvoiceDate,
				IG.InvoiceDueDate,
				IG.BillToAddress,
				IG.ShipToAddress,
				IG.Remarks,
				ISNULL(GRN.GRNNumber,'') as GRNNumber,
				IG.StatusId,
				ISNULL(SM.Title,'') as Status,
				ISNULL(VM.Title,'') AS VendorName,
				ISNULL(VM.Code,'') AS VendorCode
		from   [sPurchase].[tInvoiceGenerate] IG(nolock) 
		Left Join [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = IG.GoodsReceivedNoteID
		Left JOIN sProcurement.tVendorMaster  VM on IG.VendorId = VM.ID
		Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = IG.StatusId
		where  IG.Id=@rId AND IG.IsObsolete = 0

		select IGD.Id,
			   IGD.InvoiceGenerateId,
			   IGD.GoodsReceivedNoteDetailId,
			   IGD.OrgGroupId,
			   IGD.UnitTypeId,
			   IGD.CategoryId,
			   IGD.SubCategoryId,
			   IGD.StockItemId,
			   IGD.POQty,
			   IGD.ReceivedQty,
			   IGD.AcceptedQty,
			   IGD.RejectedQty, 
			   IGD.UnitPrice,
			   IGD.ReasonForRejection,
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tInvoiceGenerateDetail] IGD (nolock)
			   Inner JOIN	sPurchase.tInvoiceGenerate IG	ON IG.Id = IGD.InvoiceGenerateId AND IG.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = IGD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  IGD.InvoiceGenerateId=@rId

		select  AutoId,
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl
		from    sPurchase.tDocumentManagement
		where   SourceId = @rId and SourceTypeId = 2046
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pQualityCheckGet]...';


GO


ALTER PROCEDURE [sPurchase].[pQualityCheckGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  QC.Id,
				QC.QCNumber,
				QC.OrgGroupId,
				QC.LocationId,
				QC.GoodsReceivedNoteId,
				QC.PurchaseOrderId,
				QC.RequestedBy,
				ISNULL(GRN.GRNNumber,'') as GRNNumber,
				QC.StatusId,
				ISNULL(SM.Title,'') as Status
		from   [sPurchase].[tQualityCheck] QC(nolock) 
		Left Join [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = QC.GoodsReceivedNoteID
		Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = QC.StatusId
		where  QC.Id=@rId AND QC.IsObsolete = 0

		select QCD.Id,
			   QCD.QualityCheckId,
			   QCD.GoodsReceivedNoteDetailId,
			   QCD.OrgGroupId,
			   QCD.UnitTypeId,
			   QCD.CategoryId,
			   QCD.SubCategoryId,
			   QCD.StockItemId,
			   QCD.POQty,
			   QCD.ReceivedQty,
			   QCD.AcceptedQty,
			   QCD.RejectedQty,
			   QCD.ReasonForRejection, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tQualityCheckDetail] QCD (nolock)
			   Inner JOIN	sPurchase.tQualityCheck QC	ON QC.Id = QCD.QualityCheckId AND QC.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QCD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  QCD.QualityCheckId=@rId

		select  AutoId,
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl
		from    sPurchase.tDocumentManagement
		where   SourceId = @rId and SourceTypeId = 2045
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pSalesReturnGet]...';


GO


ALTER PROCEDURE [sPurchase].[pSalesReturnGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  SR.Id,
				SR.SRNumber,
				SR.OrgGroupId,
				SR.LocationId,
				SR.GoodsReceivedNoteId,
				SR.PurchaseOrderId,
				SR.RequestedBy,
				ISNULL(GRN.GRNNumber,'') as GRNNumber,
				SR.StatusId,
				ISNULL(SM.Title,'') as Status
		from   [sPurchase].[tSalesReturn] SR(nolock) 
		Left Join [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = SR.GoodsReceivedNoteID
		Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = SR.StatusId
		where  SR.Id=@rId AND SR.IsObsolete = 0

		select SRD.Id,
			   SRD.SalesReturnId,
			   SRD.GoodsReceivedNoteDetailId,
			   SRD.OrgGroupId,
			   SRD.UnitTypeId,
			   SRD.CategoryId,
			   SRD.SubCategoryId,
			   SRD.StockItemId,
			   SRD.POQty,
			   SRD.ReceivedQty,
			   SRD.RejectedQty,
			   SRD.CreditNoteIssueDate,
			   SRD.ReasonForRejection, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tSalesReturnDetail] SRD (nolock)
			   Inner JOIN	sPurchase.tSalesReturn SR	ON SR.Id = SRD.SalesReturnId AND SR.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = SRD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  SRD.SalesReturnId=@rId

		select  AutoId,
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl
		from    sPurchase.tDocumentManagement
		where   SourceId = @rId and SourceTypeId = 2044
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sWf].[pWfApprovalAdd]...';


GO


ALTER PROCEDURE [sWf].[pWfApprovalAdd]
		@rId	bigint,
	 	@rDocSourceId bigint=0,
	 	@rDocSourceTypeId smallint=0,
        @rActionEmployeeId bigint=0,
		@rActionStatusId smallint=0,
		@rActionRemark nvarchar(500) = '',
		@rIsSequancial bit=0,
		@rWfLevel int=0,
		@rWfFunctionalityId smallint=0,
		@rOrgGroupId smallint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
	BEGIN TRANSACTION
    Declare @lActionByEmployeeId bigint
	set @lActionByEmployeeId = @rActionEmployeeId

	Declare @StatusId smallint
	set @StatusId = @rActionStatusId

	IF(@rIsSequancial = 1)
	BEGIN
		Declare @HierarchyLevelId bigint
		select @HierarchyLevelId=ISNULL(AutoId,0) from [sWf].[tWfHierarchyLevel] WHERE WfApprovalActionId =@rId AND ActionByEmployeeId=@rActionEmployeeId AND StatusId <> 4
		IF(@HierarchyLevelId > 0)
		Begin
			UPDATE [sWf].[tWfHierarchyLevel] SET StatusId = @StatusId , Remark = @rActionRemark 
			WHERE AutoId = @HierarchyLevelId
		End

		IF(@rActionStatusId <> 4)
		BEGIN
			DECLARE @LogCount int
			SELECT @LogCount = COUNT(AutoId) FROM [sWf].[tWfHierarchyLevel] WHERE WfApprovalActionId = @rId
			
			IF(@rWfLevel <> @LogCount)
			Begin
				IF(@rActionStatusId = 3)
				Begin
					set @StatusId = 2
				End
				
			End
			SELECT @lActionByEmployeeId = EmployeeManagerId from [sHrm].[tEmployeeJobDetail] WHere EmployeeId = @rActionEmployeeId
			AND @lActionByEmployeeId IS NOT NULL
			
		END
	END

	IF(@rId = 0)
	BEGIN
		
		DECLARE @lNextNumber INT	 
		EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sWf.tWfApprovalAction',@lNextNumber = @lNextNumber output

		INSERT INTO sWf.tWfApprovalAction
		(
		Id,
		OrgGroupId,
		ActionEmployeeId,
		ActionStatusId,
		ActionRemark,
		DocSourceId,
		DocSourceTypeId,
		WfFunctionalityId,
		CreatedUserId,
		CreatedDateTime
		)
		VALUES
		(
			@lNextNumber,
			@rOrgGroupId,
			@rActionEmployeeId,
			@StatusId,
			@rActionRemark,
			@rDocSourceId,
			@rDocSourceTypeId,
			@rWfFunctionalityId,
			@rActionEmployeeId,
			GETUTCDATE()				
		)
		set @rId=@lNextNumber
		
		INSERT INTO sWf.tWfApprovalActionLog
		(
			WfApprovalActionId,
			ActionByEmployeeId,
			StatusId,
			IsSequancial,
			ActionRemark,
			CreatedUserId,
			CreatedDateTime
		)
		VALUES
		(
			@rId,
			@lActionByEmployeeId,
			@rActionStatusId,
			@rIsSequancial,
			@rActionRemark,
			@rActionEmployeeId,
			GETUTCDATE()				
		)

		IF(@rIsSequancial = 1 AND (@rWfLevel <> @LogCount OR @rWfLevel > 0))
		BEGIN																																																																																																																																																																				IF(@lActionByEmployeeId > 0)
			INSERT INTO [sWf].[tWfHierarchyLevel]
					(WfApprovalActionId
					,StatusId
					,Remark
					,ActionByEmployeeId
					,ActionDatetime)
				VALUES
					(@rId
					,1
					,''
					,@lActionByEmployeeId
					,sCommon.fGetDate())
		END
		SELECT 1 AS Result
	END
	ELSE
	BEGIN
		--IF EXISTS(select ID from sWf.tWfApprovalAction WHERE id = @rId AND ActionStatusId not in(3,4) OR @rIsSequancial = 0)
		--BEGIN
			UPDATE sWf.tWfApprovalAction
			SET 
			DocSourceId=@rDocSourceId,
			DocSourceTypeId=@rDocSourceTypeId,
			ActionEmployeeId=@rActionEmployeeId,
			ActionStatusId=@StatusId,
			ActionRemark=@rActionRemark,
			UpdatedUserId = @rActionEmployeeId,		
			UpdatedDateTime = GetUtcDate()
			WHERE id = @rId 

			INSERT INTO sWf.tWfApprovalActionLog
			(
				WfApprovalActionId,
				ActionByEmployeeId,
				StatusId,
				IsSequancial,
				ActionRemark,
				CreatedUserId,
				CreatedDateTime
			)
			VALUES
			(
				@rId,
				@lActionByEmployeeId,
				@rActionStatusId,
				@rIsSequancial,
				@rActionRemark,
				@rActionEmployeeId,
				GETUTCDATE()				
			)
			IF(@rIsSequancial = 1 AND @rWfLevel <> @LogCount AND @rActionStatusId <> 4)
			BEGIN																																																																																																																																																																				IF(@lActionByEmployeeId > 0)
				INSERT INTO [sWf].[tWfHierarchyLevel]
						(WfApprovalActionId
						,StatusId
						,Remark
						,ActionByEmployeeId
						,ActionDatetime)
					VALUES
						(@rId
						,1
						,''
						,@lActionByEmployeeId
						,sCommon.fGetDate())
			END
			ELSE
			BEGIN
					SELECT @lActionByEmployeeId = EmployeeManagerId from [sHrm].[tEmployeeJobDetail] WHere EmployeeId = @rActionEmployeeId
					DELETE FROM [sWf].[tWfHierarchyLevel] Where WfApprovalActionId = @rId AND ActionByEmployeeId = @lActionByEmployeeId AND @lActionByEmployeeId IS NOT NULL
			END 
			SELECT 11 AS Result 
		--END
	END	
	IF EXISTS(select ID from sWf.tWfApprovalAction WHERE id = @rId AND ActionStatusId in(3,4))
	Begin
		if(@rDocSourceTypeId = 2040)
		Begin
			update sPurchase.tPurchaseRequest 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
		else if(@rDocSourceTypeId = 2041)
		Begin
			update sPurchase.tQuotationRequest 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
		else if(@rDocSourceTypeId = 2042)
		Begin
			update sPurchase.tPurchaseOrder 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
		else if(@rDocSourceTypeId = 2043)
		Begin
			update sPurchase.tGoodsReceivedNote 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
		else if(@rDocSourceTypeId = 2044)
		Begin
			update sPurchase.tSalesReturn 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
	End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH 
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseOrderAdd]...';


GO







CREATE PROCEDURE [sPurchase].[pPurchaseOrderAdd]
		@rId bigint,
		@rPurchaseRequestId bigint,
		@rPODate datetime,	
		@rRequestedBy nvarchar(100),
		@rOrgGroupId smallint,
		@rLocationId int,
		@rStatusId smallint,	
		@rVendorId int,
		@rBillToAddress nvarchar(1000),
		@rShipToAddress nvarchar(1000),	
		@rUserId bigint,
		@rRequiredBy datetime,
		@rDetailList sPurchase.PurchaseOrderDetailType READONLY,
		@rDocumentList sPurchase.DocumentManagementType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tPurchaseOrder
			set 
				StatusId = @rStatusId,
				VendorId = @rVendorId,
				RequiredBy = @rRequiredBy,
				BillToAddress = @rBillToAddress,
				ShipToAddress = @rShipToAddress,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tPurchaseOrderDetail
			where PurchaseOrderId = @rId

			DECLARE @lNextNumberPOD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseOrderDetail',@lNextNumber = @lNextNumberPOD output
			set @lNextNumberPOD=@lNextNumberPOD-1
			INSERT INTO sPurchase.tPurchaseOrderDetail
			(
				Id,
				OrgGroupId,
				PurchaseOrderId,
				PurchaseRequestDetailId,
				StockItemId,
				TotalQty,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberPOD+Id,
					OrgGroupId,
					@rId,
					PurchaseRequestDetailId,
					StockItemId,
					TotalQty,
					Remark, 
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberPOD=@lNextNumberPOD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseOrderDetail', @rCurrentNumber = @lNextNumberPOD
			
			INSERT INTO sPurchase.tDocumentManagement
			(
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl,
				CreatedUserId,
				CreatedDateTime
			)
			select	@rOrgGroupId,
					@rId,
					2042, 
					@rUserId,
					FileName,
					Size,
					DocumentUrl,
					@rUserId, 
					GETUTCDATE() 
			from @rDocumentList

			Select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseOrder',@lNextNumber = @lNextNumber output	
			---------------select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			---------------@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tPurchaseOrder
			(
				Id,
				RefNumber,
				PurchaseRequestId,
				PODate,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				VendorId,
				RequiredBy,
				BillToAddress,
				ShipToAddress,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rPurchaseRequestId,
				@rPODate,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rVendorId,
				@rRequiredBy,
				@rBillToAddress,
				@rShipToAddress,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberPO INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseOrderDetail',@lNextNumber = @lNextNumberPO output	
			set @lNextNumberPO=@lNextNumberPO-1

	 		INSERT INTO sPurchase.tPurchaseOrderDetail
			(
				Id,
				OrgGroupId,
				PurchaseOrderId,
				PurchaseRequestDetailId,
				StockItemId,
				TotalQty,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberPO+Id,
					OrgGroupId,
					@rId,
					PurchaseRequestDetailId,
					StockItemId,
					TotalQty,
					Remark, 
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberPO=@lNextNumberPO+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseOrderDetail', @rCurrentNumber = @lNextNumberPO
			
			INSERT INTO sPurchase.tDocumentManagement
			(
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl,
				CreatedUserId,
				CreatedDateTime
			)
			select	@rOrgGroupId,
					@rId,
					2042, 
					@rUserId,
					FileName,
					Size,
					DocumentUrl,
					@rUserId, 
					GETUTCDATE() 
			from @rDocumentList

			Select @rId

			Declare @typeId smallint=0
			Declare @Level smallint=0
			SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 3
			IF(@typeId = 1)--parallel
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2042,@rUserId,1,'',0,0,3,@rOrgGroupId
			END
			ELSE IF(@typeId = 2)--sequencial
			Begin
				exec [sWf].[pWfApprovalAdd] 0,@rId,2042,@rUserId,1,'',1,@Level,3,@rOrgGroupId
			End
			ELSE IF(@typeId = 3)--auto approved
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2042,@rUserId,3,'',0,0,3,@rOrgGroupId
			END
			--select 1;
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseRequestAdd]...';


GO




CREATE PROCEDURE [sPurchase].[pPurchaseRequestAdd]
		@rId bigint,
		@rRequestDate datetime,
		@rResourceId int,
		@rRequestedBy nvarchar(100),
		@rOrgGroupId smallint,
		@rBranchId int,
		@rLocationId int,
		@rStatusId smallint,	
		@rVendorId int,
		@rUserId bigint,	
		@rRequiredBy datetime,	
		@rDetailList sPurchase.PurchaseRequestDetailType READONLY,
		@rDocumentList sPurchase.DocumentManagementType READONLY

 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tPurchaseRequest
			set
				--RequestedBy = @rRequestedBy,	 
				StatusId = @rStatusId,
				--VendorId = @rVendorId,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tPurchaseRequestDetail
			where PurchaseRequestId = @rId

			DECLARE @lNextNumberPRQA INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseRequestDetail',@lNextNumber = @lNextNumberPRQA output
			set @lNextNumberPRQA=@lNextNumberPRQA-1
			INSERT INTO sPurchase.tPurchaseRequestDetail
			(
				ID,
				OrgGroupId,
				PurchaseRequestId,
				StockItemId,
				RequestedQty,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberPRQA+Id,
					@rOrgGroupId,
					@rId, 
					StockItemId,
					RequestedQty,
					Remark, 
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberPRQA=@lNextNumberPRQA+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseRequestDetail', @rCurrentNumber = @lNextNumberPRQA

			INSERT INTO sPurchase.tDocumentManagement
			(
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl,
				CreatedUserId,
				CreatedDateTime
			)
			select	@rOrgGroupId,
					@rId,
					2040, 
					@rUserId,
					FileName,
					Size,
					DocumentUrl,
					@rUserId, 
					GETUTCDATE() 
			from @rDocumentList

			Select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseRequest',@lNextNumber = @lNextNumber output	
			--select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			--@rNextNumber = @loNextNumber OUTPUT
	 		INSERT INTO sPurchase.tPurchaseRequest
			(
				Id,
				Number,
				RequestDate,
				ResourceId,
				RequestedBy, 
				OrgGroupId,
				BranchId,
				LocationId, 			 
				StatusId,
				VendorId,
				RequiredBy,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rRequestDate,
				@rResourceId,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rBranchId,
				@rLocationId, 		 
				@rStatusId,
				@rVendorId,
				@rRequiredBy,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			DECLARE @lNextNumberPRQ INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseRequestDetail',@lNextNumber = @lNextNumberPRQ output	
			set @lNextNumberPRQ=@lNextNumberPRQ-1

	 		INSERT INTO sPurchase.tPurchaseRequestDetail
			(
				Id,
				OrgGroupId,
				PurchaseRequestId,
				StockItemId,
				RequestedQty,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberPRQ+Id,
					@rOrgGroupId,
					@rId, 
					StockItemId,
					RequestedQty,
					Remark, 
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberPRQ=@lNextNumberPRQ+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseRequestDetail', @rCurrentNumber = @lNextNumberPRQ


			INSERT INTO sPurchase.tDocumentManagement
			(
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl,
				CreatedUserId,
				CreatedDateTime
			)
			select	@rOrgGroupId,
					@rId,
					2040, 
					@rUserId,
					FileName,
					Size,
					DocumentUrl,
					@rUserId, 
					GETUTCDATE() 
			from @rDocumentList
			
			select @rId

			Declare @typeId smallint=0
			Declare @Level smallint=0
			SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 1
			IF(@typeId = 1)--parallel
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2040,@rUserId,1,'',0,0,1,@rOrgGroupId
			END
			ELSE IF(@typeId = 2)--sequencial
			Begin
				exec [sWf].[pWfApprovalAdd] 0,@rId,2040,@rUserId,1,'',1,@Level,1,@rOrgGroupId
			End
			ELSE IF(@typeId = 3)--auto approved
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2040,@rUserId,3,'',0,0,1,@rOrgGroupId
			END
			
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pQuotationRequestAdd]...';


GO




CREATE PROCEDURE [sPurchase].[pQuotationRequestAdd]
		@rId bigint,
		@rOrgGroupId smallint,
		@rBranchId int,
		@rLocationId int,
		@rPurchaseRequestId bigint,
		@rName varchar(100),
		@rRFQDate datetime,
		@rDescription nvarchar(300),
		@rStartDate datetime,
		@rEndDate datetime,
		@rBidOpen nvarchar(100),
		@rBidClose nvarchar(100),
		@rPersonContact bigint,
		@rEmail nvarchar(100),
		@rSendToVendor bit,
		@rStatusId int,
		@rVendorId int,
		@rUserId bigint,
		@rDetailList sPurchase.QuotationRequestDetailType READONLY,
		@rDocumentList sPurchase.DocumentManagementType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		If(@rId > 0)
		Begin
			Update sPurchase.tQuotationRequest
			set
				OrgGroupId =@rOrgGroupId,
				BranchId =@rBranchId,
				LocationId =@rLocationId,
				PurchaseRequestId =@rPurchaseRequestId,
				Name =@rName,
				RFQDate =@rRFQDate,
				Description =@rDescription,
				StartDate =@rStartDate,
				EndDate =@rEndDate,
				BidOpen =@rBidOpen,
				BidClose =@rBidClose,
				PersonContact =@rPersonContact,
				Email =@rEmail,
				SendToVendor =@rSendToVendor,
				StatusId =@rStatusId,
				VendorId =@rVendorId,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tQuotationRequestDetail
			where QuotationRequestId = @rId

			DECLARE @lNextNumberQRDA INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQuotationRequestDetail',@lNextNumber = @lNextNumberQRDA output
			SET @lNextNumberQRDA=@lNextNumberQRDA-1
			INSERT INTO sPurchase.tQuotationRequestDetail
			(
				Id,
				OrgGroupId,
				QuotationRequestId,
				PurchaseRequestDetailId,
				StockItemId,
				RequestedQty,
				Remark,
				TargetPrice,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberQRDA+Id,
				    OrgGroupId,
					@rId,
					PurchaseRequestDetailId, 
					StockItemId,
					RequestedQty,
					Remark,
					TargetPrice,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberQRDA=@lNextNumberQRDA+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQuotationRequestDetail', @rCurrentNumber = @lNextNumberQRDA

			INSERT INTO sPurchase.tDocumentManagement
			(
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl,
				CreatedUserId,
				CreatedDateTime
			)
			select	@rOrgGroupId,
					@rId,
					2041, 
					@rUserId,
					FileName,
					Size,
					DocumentUrl,
					@rUserId, 
					GETUTCDATE() 
			from @rDocumentList
			select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQuotationRequest',@lNextNumber = @lNextNumber output	
			-------------select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			-------------@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tQuotationRequest
			(
				Id,
				Number,
				OrgGroupId,
				BranchId,
				LocationId,
				PurchaseRequestId,
				Name,
				RFQDate,
				Description,
				StartDate,
				EndDate,
				BidOpen,
				BidClose,
				PersonContact,
				Email,
				SendToVendor,
				StatusId,
				VendorId,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rOrgGroupId,
				@rBranchId ,
				@rLocationId,
				@rPurchaseRequestId,
				@rName,
				@rRFQDate,
				@rDescription,
				@rStartDate,
				@rEndDate ,
				@rBidOpen ,
				@rBidClose,
				@rPersonContact,
				@rEmail,
				@rSendToVendor,
				@rStatusId,
				@rVendorId ,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber 

			DECLARE @lNextNumberQRD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQuotationRequestDetail',@lNextNumber = @lNextNumberQRD output
			SET @lNextNumberQRD=@lNextNumberQRD+1
	 		INSERT INTO sPurchase.tQuotationRequestDetail
			(
				Id,
				OrgGroupId,
				QuotationRequestId,
				PurchaseRequestDetailId,
				StockItemId,
				RequestedQty,
				Remark,
				TargetPrice,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberQRD+Id,
				    OrgGroupId,
					@rId,
					PurchaseRequestDetailId, 
					StockItemId,
					RequestedQty,
					Remark,
					TargetPrice,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberQRD=@lNextNumberQRD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQuotationRequestDetail', @rCurrentNumber = @lNextNumberQRD

			INSERT INTO sPurchase.tDocumentManagement
			(
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl,
				CreatedUserId,
				CreatedDateTime
			)
			select	@rOrgGroupId,
					@rId,
					2041, 
					@rUserId,
					FileName,
					Size,
					DocumentUrl,
					@rUserId, 
					GETUTCDATE() 
			from @rDocumentList
			select @rId

			Declare @typeId smallint=0
			Declare @Level smallint=0
			SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 2
			IF(@typeId = 1)--parallel
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,1,'',0,0,2,@rOrgGroupId
			END
			ELSE IF(@typeId = 2)--sequencial
			Begin
				exec [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,1,'',1,@Level,2,@rOrgGroupId
			End
			ELSE IF(@typeId = 3)--auto approved
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,3,'',0,0,2,@rOrgGroupId
			END
			--select 1;
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pSalesReturnAdd]...';


GO




CREATE PROCEDURE [sPurchase].[pSalesReturnAdd]
		@rId bigint,
		@rGoodsReceivedNoteId bigint,
		@rPurchaseOrderId bigint,
		@rRequestedBy nvarchar(100),
		@rOrgGroupId int,
		@rLocationId int,
		@rStatusId smallint,	
		@rUserId bigint,
		@rDetailList sPurchase.SalesReturnDetailType READONLY,
		@rDocumentList sPurchase.DocumentManagementType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tSalesReturn
			set 
				StatusId = @rStatusId,
				GoodsReceivedNoteId = @rGoodsReceivedNoteId,
				PurchaseOrderId = @rPurchaseOrderId,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tSalesReturnDetail
			where SalesReturnId = @rId

			DECLARE @lNextNumberSRD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tSalesReturnDetail',@lNextNumber = @lNextNumberSRD output
			set @lNextNumberSRD=@lNextNumberSRD-1
			INSERT INTO sPurchase.tSalesReturnDetail
			(
				Id,
				OrgGroupId,
				SalesReturnId,
				GoodsReceivedNoteDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				RejectedQty,
				CreditNoteIssueDate,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberSRD+Id,
					OrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					RejectedQty,
					CreditNoteIssueDate,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberSRD=@lNextNumberSRD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tSalesReturnDetail', @rCurrentNumber = @lNextNumberSRD
			
			INSERT INTO sPurchase.tDocumentManagement
			(
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl,
				CreatedUserId,
				CreatedDateTime
			)
			select	@rOrgGroupId,
					@rId,
					2044, 
					@rUserId,
					FileName,
					Size,
					DocumentUrl,
					@rUserId, 
					GETUTCDATE() 
			from @rDocumentList
			select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tSalesReturn',@lNextNumber = @lNextNumber output	
			-------------select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			------------@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tSalesReturn
			(
				Id,
				SRNumber,
				GoodsReceivedNoteId,
				PurchaseOrderId,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rGoodsReceivedNoteId,
				@rPurchaseOrderId,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberSRDD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tSalesReturnDetail',@lNextNumber = @lNextNumberSRDD output	
			set @lNextNumberSRDD=@lNextNumberSRDD-1

	 		INSERT INTO sPurchase.tSalesReturnDetail
			(
				Id,
				OrgGroupId,
				SalesReturnId,
				GoodsReceivedNoteDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				RejectedQty,
				CreditNoteIssueDate,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberSRDD+Id,
					OrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					RejectedQty,
					CreditNoteIssueDate,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberSRDD=@lNextNumberSRDD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tSalesReturnDetail', @rCurrentNumber = @lNextNumberSRDD
			
			INSERT INTO sPurchase.tDocumentManagement
			(
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl,
				CreatedUserId,
				CreatedDateTime
			)
			select	@rOrgGroupId,
					@rId,
					2044, 
					@rUserId,
					FileName,
					Size,
					DocumentUrl,
					@rUserId, 
					GETUTCDATE() 
			from @rDocumentList
			select @rId

			Declare @typeId smallint=0
			Declare @Level smallint=0
			SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 5
			IF(@typeId = 1)--parallel
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2044,@rUserId,1,'',0,0,5,@rOrgGroupId
			END
			ELSE IF(@typeId = 2)--sequencial
			Begin
				exec [sWf].[pWfApprovalAdd] 0,@rId,2044,@rUserId,1,'',1,@Level,5,@rOrgGroupId
			End
			ELSE IF(@typeId = 3)--auto approved
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2044,@rUserId,3,'',0,0,5,@rOrgGroupId
			END
			--select 1;
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pInvoiceGenerateAdd]...';


GO



CREATE PROCEDURE [sPurchase].[pInvoiceGenerateAdd]
		@rId bigint,
		@rGoodsReceivedNoteId bigint,
		@rVendorId bigint,
		@rRequestedBy nvarchar(100),
		@rOrgGroupId int,
		@rLocationId int,
		@rStatusId smallint,
		@rInvoiceDate datetime,
		@rInvoiceDueDate datetime,
		@rBillToAddress nvarchar(1000),
		@rShipToAddress nvarchar(1000),
		@rRemarks nvarchar(500),	
		@rUserId bigint,
		@rDetailList sPurchase.InvoiceGenerateDetailType READONLY,
		@rDocumentList sPurchase.DocumentManagementType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tInvoiceGenerate
			set 
				StatusId = @rStatusId,
				GoodsReceivedNoteId = @rGoodsReceivedNoteId,
				VendorId = @rVendorId,
				InvoiceDate = @rInvoiceDate,
				InvoiceDueDate = @rInvoiceDueDate,
				BillToAddress = @rBillToAddress,
				ShipToAddress = @rShipToAddress,
				Remarks = @rRemarks,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tInvoiceGenerateDetail
			where InvoiceGenerateId = @rId

			DECLARE @lNextNumberIGD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tInvoiceGenerateDetail',@lNextNumber = @lNextNumberIGD output
			set @lNextNumberIGD=@lNextNumberIGD-1
			INSERT INTO sPurchase.tInvoiceGenerateDetail
			(
				Id,
				OrgGroupId,
				InvoiceGenerateId,
				GoodsReceivedNoteDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				AcceptedQty,
				RejectedQty,
				UnitPrice,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberIGD+Id,
					OrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					UnitPrice,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberIGD=@lNextNumberIGD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tInvoiceGenerateDetail', @rCurrentNumber = @lNextNumberIGD
			
			INSERT INTO sPurchase.tDocumentManagement
			(
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl,
				CreatedUserId,
				CreatedDateTime
			)
			select	@rOrgGroupId,
					@rId,
					2046, 
					@rUserId,
					FileName,
					Size,
					DocumentUrl,
					@rUserId, 
					GETUTCDATE() 
			from @rDocumentList
			Select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tInvoiceGenerate',@lNextNumber = @lNextNumber output	
			--select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			--@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tInvoiceGenerate
			(
				Id,
				INVNumber,
				GoodsReceivedNoteId,
				VendorId,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				InvoiceDate,
				InvoiceDueDate,
				BillToAddress,
				ShipToAddress,
				Remarks,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rGoodsReceivedNoteId,
				@rVendorId,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rInvoiceDate,
				@rInvoiceDueDate,
				@rBillToAddress,
				@rShipToAddress,
				@rRemarks,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberIGDD INT= 10000 + 	(select count (ID) from sPurchase.tInvoiceGenerateDetail)	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tInvoiceGenerateDetail',@lNextNumber = @lNextNumberIGDD output	
			set @lNextNumberIGDD=@lNextNumberIGDD-1

	 		INSERT INTO sPurchase.tInvoiceGenerateDetail
			(
				Id,
				OrgGroupId,
				InvoiceGenerateId,
				GoodsReceivedNoteDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				AcceptedQty,
				RejectedQty,
				UnitPrice,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberIGDD+Id,
					OrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					UnitPrice,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberIGDD=@lNextNumberIGDD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tInvoiceGenerateDetail', @rCurrentNumber = @lNextNumberIGDD

			INSERT INTO sPurchase.tDocumentManagement
			(
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl,
				CreatedUserId,
				CreatedDateTime
			)
			select	@rOrgGroupId,
					@rId,
					2046, 
					@rUserId,
					FileName,
					Size,
					DocumentUrl,
					@rUserId, 
					GETUTCDATE() 
			from @rDocumentList
			select @rId
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pInvoiceGenerateSearchGet]...';


GO


ALTER PROCEDURE [sPurchase].[pInvoiceGenerateSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				IG.Id,
				--GRN.PurchaseRequestId,
				--GRN.PurchaseOrderId,
				--GRN.DepartmentBranchId,
				--GRN.VendorId,
				IG.INVNumber as Number,
				IG.RequestedBy, 
				IG.LocationId,
				ISNULL(SM.Title,'') as Status
		FROM		
				sPurchase.tInvoiceGenerate IG (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on IG.StatusId = SM.Id
		WHERE 
				((IG.INVNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((IG.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((IG.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND IG.IsObsolete = 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sAlert].[pAlertQueueDashboardGet]...';


GO
ALTER PROCEDURE [sAlert].[pAlertQueueDashboardGet]
	@rOrgGroupId int =0,
	@rFromDate date = '',
	@rToDate date = '',
	@rTypeId smallint = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rTypeId = 1) -- OrgGroup wise Summary
	BEGIN
		SELECT 
			OGM.Id AS OrgGroupId, 
			OGM.Title AS OrgGroupTitle, 
			COUNT(AQL.AutoId) AS QueueAlertTotal, 
			COUNT(QL.Id) AS ReceivedQueueAlertTotal,
			COUNT(AQL.AutoId) - COUNT(QL.Id) AS PendingQueueAlertTotal
		FROM sAlert.tAlertQueueLog AQL
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = AQL.OrgId
		LEFT JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
		LEFT JOIN NVQueue.dbo.QueueLog QL ON AQL.AutoId = QL.MessageId
		WHERE OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0
			AND (AQL.CreatedDateTime >= @rFromDate OR ISNULL(@rFromDate, '') = '')
			AND (AQL.CreatedDateTime <= @rToDate OR ISNULL(@rToDate, '') = '')
		GROUP BY OGM.Id, OGM.Title
	END
	IF(@rTypeId = 2) -- Organization wise Summary
	BEGIN
		SELECT 
			AQL.OrgId AS OrgId, 
			OM.Title AS OrganizationTitle,
			COUNT(AQL.AutoId) AS QueueAlertTotal, 
			COUNT(QL.Id) AS ReceivedQueueAlertTotal,
			COUNT(AQL.AutoId) - COUNT(QL.Id) AS PendingQueueAlertTotal
		FROM sAlert.tAlertQueueLog AQL
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = AQL.OrgId
		LEFT JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
		LEFT JOIN NVQueue.dbo.QueueLog QL ON AQL.AutoId = QL.MessageId
		WHERE OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0
			AND (AQL.CreatedDateTime >= @rFromDate OR ISNULL(@rFromDate, '') = '')
			AND (AQL.CreatedDateTime <= @rToDate OR ISNULL(@rToDate, '') = '')
		GROUP BY AQL.OrgId, OM.Title
	END
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricFirstInTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricFirstInTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime,
	@rEventId int=127
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 

			--For Optimization
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=95),0)

			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 ),'')
			--For Optimization

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
					SourceId bigint NOT NULL,
					In_Out_Time [datetime] NOT NULL,
					SourceTypeId int NOT NULL,
					CreatedDateTime [datetime] NOT NULL,
					AutoId bigint not null--For Optimization
				)
			insert into #tTable
			select SourceId,min(In_Out_Time),SourceTypeId,min(CreatedDateTime) 
			,min(Autoid) --For Optimization
			from [sBiometric].[tCloudTransactionData]  
			WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]()) AND SourceTypeId=95 
			--For Optimization
			AND Autoid>@lCloudTransactionDataId
			AND SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=95 and cast(CreatedDateTime as date)=CONVERT(date,[sCommon].[fGetDate]()))
			--For Optimization
			Group by SourceId,SourceTypeId
	
			--select * from #tTable
			--For Optimization
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				'' AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS StudentName,
				EM.Code AS Code,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				@rEventId,
				@AlertUniqueId
			FROM 
				#tTable temp
				Inner join sHrm.vEmployeeCommonDetail EM ON temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				--temp.CreatedDateTime >= DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]())
				temp.CreatedDateTime < @rToDateTime
				AND temp.CreatedDateTime >= @rFromDateTime
				AND EM.OrgID =@rOrgId
				--AND E.EmployeeStatusId = 7  -- Added

			SELECT 
				MobileNo,	
				EmailId,
				replace (
				replace (
				replace (
				replace(@lSMSTemplete,'[EmployeeName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				AS SMSText,
				replace (
				replace (
				replace (
				replace(@lMailTemplete,'[EmployeeName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				AS MailText,
				replace (
				replace (
				replace (
				replace(@lNotificationTemplete,'[EmployeeName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				AS NotificationText,
				replace (
				replace (
				replace (
				replace(@lWhatsappTemplete,'[EmployeeName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				AS WhatsappText,
				Subject,
				ReceiverSourceTypeId,
				ReceiverSourceId,
				StudentName AS EmployeeName,
				Code,
				WhatsAppContactNo,
				SourceTypeId,
				SourceId,
				OrgId,
				OrgGroupId,
				Time,
				OrganizationTitle
			FROM 
				sBiometric.tTempBiometricAlertData
			where 
				AlertUniqueId=@AlertUniqueId

			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH


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


GO
ALTER PROCEDURE [sAlert].[pEmployeeBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime=null,
	@rFromDateTime DateTime=null
 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=128 and SourceTypeId=95),0)
			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 1 ),'')
			--declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)
	 
			--select * from #tShift
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						OutTimeAlertTime time NOT NULL,
						CreatedDateTime [datetime] NOT NULL,
				AutoId bigint not null
					)
			--if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,cast(SMC.OutTimeAlertTime as time),Max(CreatedDateTime) ,min(CDT.Autoid)
				from [sBiometric].[tCloudTransactionData] CDT 
				INNER JOIN sBiometric.tShiftMasterCloud SMC on SMC.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 
				AND SMC.IsOutTimeAlertTime=1
				AND CAST(OutTimeAlertTime AS Time) > CAST(CDT.In_Out_Time AS Time)
				Group by SourceId,SourceTypeId,SMC.OutTimeAlertTime
			END

			--select * from #tTable
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				'' AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS StudentName,
				EM.Code AS Code,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				128,
				@AlertUniqueId
			FROM 
				#tTable temp
				Inner join sHrm.vEmployeeCommonDetail EM ON temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				
				temp.OutTimeAlertTime < cast(@rToDateTime as Time)
				AND temp.OutTimeAlertTime >= Cast(@rFromDateTime As Time)
				AND EM.OrgID =@rOrgId

			select 
					MobileNo,	
					EmailId,
					replace (
					replace(@lSMSTemplete,'[EmployeeName]',StudentName),
					'[TimeStamp]',ISNULL(Convert(varchar,Time,108),''))
					 AS SMSText,
					replace (
					replace(@lMailTemplete,'[EmployeeName]',StudentName),
					'[TimeStamp]',ISNULL(Convert(varchar,Time,108),''))
					 AS MailText,
					replace (
					replace(@lNotificationTemplete,'[EmployeeName]',StudentName),
					'[TimeStamp]',ISNULL(Convert(varchar,Time,108),''))
					 AS NotificationText,
					replace (
					replace(@lWhatsappTemplete,'[EmployeeName]',StudentName),					
					'[TimeStamp]',ISNULL(Convert(varchar,Time,108),''))
					 AS WhatsappText,
					Subject,
					ReceiverSourceTypeId,
					ReceiverSourceId,
					StudentName AS EmployeeName,
					Code,
					WhatsAppContactNo,
					SourceTypeId,
					SourceId,
					OrgId,
					OrgGroupId,
					OrganizationTitle
				FROM  
					sBiometric.tTempBiometricAlertData
				where 
					AlertUniqueId=@AlertUniqueId


			DROP TABLE #tTable
			--DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricLateTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricLateTimeGet]
	 	 
	 	 @rOrgId int,
		 @rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)='',
		@rEventId int=137,
		@rShiftCode int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lDate date = ''
	SET @lDate = sCommon.fGetDate()

	DECLARE @lDay as nvarchar(3)

	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

	DECLARE @lColumnName varchar(10) = '',@lShiftColumntName varchar(10) = ''
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'
	SET @lShiftColumntName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_S'

	DECLARE @lGetConfigTime nvarchar(20) = ''
	SELECT @lGetConfigTime =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 398 AND SourceId = @rOrgId

			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 ),'')
	--IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime) > 0)
	--BEGIN
	DECLARE @Query NVARCHAR(MAX) = ''
	print (@Query)
	SET @Query = 'SELECT
					EC.MobileNumber AS MobileNo,	
					EC.CompanyEmail AS EmailId,
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MsgText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lSMSTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS SMSText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lMailTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MailText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lNotificationTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS NotificationText,
					  replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lWhatsappTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS WhatsappText,
					'''+CONVERT(nvarchar(20),@rSubject)+''' AS Subject,
					95 AS ReceiverSourceTypeId,
					EC.EmployeeId AS ReceiverSourceId,
					EC.EmployeeName AS EmployeeName,
					ISNULL(EC1.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					95 AS SourceTypeId,
					EC.EmployeeId AS SourceId,
					EC.OrgId,
					OM.OrgGroupId,
					EM.Id AS EmployeeId,
					EM.Code,
					ISNULL(EM.FirstName, '''') + '' '' + ISNULL(EM.LastName, '''') AS  EmployeeName,
					 '+@lColumnName+' AS Time,
					OM.DisplayTitle AS OrganizationTitle
		FROM 
				sHrm.tEmployeeMaster EM
				Inner join sHrm.vEmployeeCommonDetail EC ON EM.Id=EC.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC1 ON EC1.EmployeeId = EC.EmployeeId
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = EM.Id AND MT.SourceTypeId = 95 
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
				INNER Join sBiometric.tShiftMasterCloud SM ON SM.ShiftName='+CONVERT(nvarchar(20),@lShiftColumntName)+' And (SM.ShiftCode='+CONVERT(nvarchar(20),@rShiftCode)+' OR '+CONVERT(nvarchar(20),@rShiftCode)+'=0)
		WHERE
				EM.OrgID = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MONTH(MT.Attn_dt) = MONTH('''+CONVERT(nvarchar(20),@lDate)+''')
				AND '+@lColumnName+' > DATEADD(minute, SM.GraceAfter,SM.StartTime)
				--AND '+@lColumnName+' > '''+@lGetConfigTime+'''
				AND EM.StatusId = 7	'
		print (@Query)
		execute (@Query)	
	--END

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


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricLateTimeGet]
	 	 
	 	 @rOrgId int,
		@rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)='',
		@rEventId int=137,
		@rShiftCode int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lDate date = ''
	SET @lDate = sCommon.fGetDate()

	DECLARE @lDay as nvarchar(3)
	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

	DECLARE @lColumnName varchar(10) = '',@lShiftColumntName varchar(10) = ''
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'
	SET @lShiftColumntName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_S'

	DECLARE @lGetConfigTime nvarchar(20) = ''
	SELECT @lGetConfigTime =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 399 AND SourceId = @rOrgId

	declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
	set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
	set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
	set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
	set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
	set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 ),'')
	--IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime) > 0)
	--BEGIN
	DECLARE @Query NVARCHAR(MAX) = ''
	SET @Query ='SELECT
					SC.ParentContactNo AS MobileNo,	
					SC.ParentEmail AS EmailId,
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MsgText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lSMSTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS SMSText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lMailTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MailText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lNotificationTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS NotificationText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lWhatsappTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS WhatsappText,
					'''+CONVERT(nvarchar(20),@rSubject)+''' AS Subject,
					2003 AS ReceiverSourceTypeId,
					SC.StudentId AS ReceiverSourceId,
					sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId) AS StudentName,
					ISNULL(SC.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					2003 AS SourceTypeId,
					SC.StudentId AS SourceId,
					SM.OrgId,
					OM.OrgGroupId,
					SM.Id AS StudentId,
					SM.Code,
					sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId) AS  StudentName,
					 '+@lColumnName+' AS Time,
					OM.DisplayTitle AS OrganizationTitle	
		FROM 
				sStudent.tStudentMaster SM
				Inner join sStudent.tStudentCommunication SC ON SM.Id=SC.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgID = OM.Id
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = SM.Id AND MT.SourceTypeId = 2003
				INNER Join sBiometric.tShiftMasterCloud SMC ON SMC.ShiftName='+@lShiftColumntName+' And (SMC.ShiftCode='+CONVERT(nvarchar(20),@rShiftCode)+' OR '+CONVERT(nvarchar(20),@rShiftCode)+'=0)
		WHERE
				SM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MONTH(MT.Attn_dt) = MONTH('''+CONVERT(nvarchar(20),@lDate)+''')
				--AND '+@lColumnName+' > '''+@lGetConfigTime+'''
				AND '+@lColumnName+' > DATEADD(minute, SMC.GraceAfter,SMC.StartTime)
				AND SM.StatusId = 1'
				
		print (@Query)
		execute (@Query)			
	--END

END
GO
PRINT N'Altering Procedure [sAssessment].[pMarkEntryAllExamSubjectGet]...';


GO
ALTER PROCEDURE [sAssessment].[pMarkEntryAllExamSubjectGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId nvarchar(Max),
	 @rBatchId int,
	 @rClassSubjectId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

DECLARE @ExamIDTable TABLE (ExamID BIGINT)
INSERT INTO @ExamIDTable(ExamID)
SELECT item FROM sCommon.fnSplit(@rExamId,',')

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(E.Id) 
					  From sAssessment.vExamMaster  E
					  --INNER JOIN sAssessment.tExamDetail Ed ON Ed.ExamId =E.Id 
					   Where ClassId = @rClassId AND E.Id in (SELECT ExamID FROM @ExamIDTable)
					   Order by E.OrderIndex --E.ExamSubGroupId -- Changed for mantis 0028212 by foram
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        --select @cols
set @query = 'SELECT  AcademicId, Name,RollNo,Code,ClassName, ' + @cols + '
FROM
(
Select ISNULL(RD.Obtain,0) AS Obtain, A.AcademicId,ED.ExamId,A.Name,A.RollNo,
A.Code,CM.Title ClassName 
FROM sStudent.vStudentAcademic A 
INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.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=A.AcademicId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectID
LEFT JOIN sAssessment.tOptionalSubject OP ON OP.AcademicId=A.AcademicId ANd CS.Id=OP.ClassSubjectId  
WHERE A.StatusId =1   AND A.BatchId = '+ CONVERT(nvarchar(15),@rBatchId) + ' AND A.ClassId= ' + convert(nvarchar(15),@rClassId) +  '  And A.DivisionId= ' + convert(nvarchar(15),@rDivisionId) + ' And  ED.ExamId in( ' + convert(nvarchar(Max),@rExamId) + ') 
And ED.ClassSubjectId='+convert(nvarchar(14),@rClassSubjectId)+'  AND ((CS.IsOptional = 1 AND  isnull(oP.AcademicId,0) <> 0) OR (CS.IsOptional = 0)) 
 ) MAIN

PIVOT
(
	MAX(obtain )
FOR ExamID IN (' + @cols + ')
)pvt Order by RollNo'
  --print @query
execute(@query)
		
END
GO
PRINT N'Altering Procedure [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	
	 
	 -- decimal Percentage Based on Config Assessment.IsShowPercentageRoundoff - mantisid - 0028336

	 DECLARE @lOrgGroupId int
	 SELECT @lOrgGroupId = OM.OrgGroupId From sSetup.tBatchMaster BM
					  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					  Where BM.Id = @rBatchId

	 DECLARE @lPercentageConfigValue bit
	 SELECT @lPercentageConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 538 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupId,4)
	 --SELECT @lPercentageConfigValue

	 --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
	Percentage = CASE WHEN @lPercentageConfigValue = 1 THEN ROUND((A.Obtain/A.Maximum)*100,0) ELSE (A.Obtain/A.Maximum)*100 END
	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
	Percentage = CASE WHEN @lPercentageConfigValue = 1 THEN ROUND((A.Obtain/A.Maximum)*100,0) ELSE (A.Obtain/A.Maximum)*100 END
	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 ERROR_MESSAGE()
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptAllClassSubjectGradeAnalysis]...';


GO


ALTER PROCEDURE [sAssessment].[pRptAllClassSubjectGradeAnalysis]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rDepartmentId 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 @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 = @rExamSubGroupId AND BatchId=@rBatchId AND (ClassId = @rClassId OR @rClassId = 0))

	 --According to AssessmentConfiguration
	 Set @GradeSetId = (Select AnalysisGradeSetId from sAssessment.tConfiguration Where OrgId = @rOrgId)
		  --Select @GradeSetId
	CREATE Table #Temp
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2),
	)
	Insert into #Temp
	
		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId
	 
	 	 Set @G1=(Select GradeCode from #Temp where Id=1) 
	 	 Set @G2=(Select GradeCode from #Temp where Id=2) 
	 	 Set @G3=(Select GradeCode from #Temp where Id=3) 
	 	 Set @G4=(Select GradeCode from #Temp where Id=4) 
	     Set @G5=(Select GradeCode from #Temp where Id=5) 
         Set @G6=(Select GradeCode from #Temp where Id=6) 
	     Set @G7=(Select GradeCode from #Temp where Id=7) 
	 	 Set @G8=(Select GradeCode from #Temp where Id=8) 
	 	 Set @G9=(Select GradeCode from #Temp where Id=9) 
		 Set @G10=(Select GradeCode from #Temp where Id=10)  
	   
	 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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS LowestPerMark ,
	  
	  (Select COUNT(R.AcademicId) 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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G1  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount1,
	  
  (Select COUNT(R.AcademicId) 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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G2  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount2,
	 

  (Select COUNT(R.AcademicId)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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G3  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount3,
	 

  (Select COUNT(R.AcademicId) 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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G4  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount4,
	 
  (Select COUNT(R.AcademicId) 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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G5  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount5,
	 
  (Select COUNT(R.AcademicId) 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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G6  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount6,
	 
  (Select COUNT(R.AcademicId) 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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G7  AND CS.SubjectId=SM.Id  AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount7,
	 
  (Select COUNT(R.AcademicId) 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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G8  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount8,
	 
  (Select COUNT(R.AcademicId) 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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G9  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount9,
	 
  (Select COUNT(R.AcademicId) 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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G10  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount10,
	  
	  
   
	  ISNULL(@G1,'*') AS Grade1,
	  ISNULL(@G2,'*') AS Grade2,
	  ISNULL(@G3,'*') AS Grade3,
	  ISNULL(@G4,'*') AS Grade4,
	  ISNULL(@G5,'*') As Grade5,
	  ISNULL(@G6,'*') As Grade6,
	  ISNULL(@G7,'*') AS Grade7,
	  ISNULL(@G8,'*') AS Grade8,
	  ISNULL(@G9,'*') AS Grade9,
	 ISNULL(@G10,'*')  AS Grade10,
	 Sm.Id AS SubjectId,
	  SM.Title AS SubjectName,
	  CS.OrderIndex AS OrderIndex,
	  (select COUNT(R.AcademicId) 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 ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id 
			AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND ISNULL(RD.IsPresent,0) = 0 
		) AS AbsentCount
	  

	 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 (CLM.DepartmentId=@rDepartmentId OR @rDepartmentId=0)	
			AND (ISNULL(CLM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			AND CLM.IsObsolete = 0 AND DM.IsObsolete=0
  	
END

-- SP Drag and Drop
--BEGIN
	--SELECT 
	-- '' AS Builder1,
	-- 0 AS ClassId,
	-- 0 AS DivisionId,
	-- '' AS ClassName,
	-- '' AS DivisionName,
	-- 0 AS NoOfStudent,
	-- Convert(DECIMAL,0) HighestPerMark,
	-- Convert(DECIMAL,0) AveragePerMark,
	-- Convert(DECIMAL,0) LowestPerMark,
	-- 0 AS GradeCount1,
	-- 0 AS GradeCount2,
	-- 0 AS GradeCount3,
	-- 0 AS GradeCount4,
	-- 0 AS GradeCount5,
	-- 0 AS GradeCount6,
	-- 0 AS GradeCount7,
	-- 0 AS GradeCount8,
	-- 0 AS GradeCount9,
	-- 0 AS GradeCount10,
	-- '' AS Grade1,
	-- '' AS Grade2,
	-- '' AS Grade3,
	-- '' AS Grade4,
	-- '' AS Grade5,
	-- '' AS Grade6,
	-- '' AS Grade7,
	-- '' AS Grade8,
	-- '' AS Grade9,
	-- '' AS Grade10,
	-- 0 AS SubjectId,
	-- '' AS SubjectName,
	-- 0 AS OrderIndex,
	-- 0 AS AbsentCount

--END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetCoScholasticSubSingleGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptResultSheetCoScholasticSubSingleGet]
	 --@rExamId int,
	 --@rAcademicId bigint
	 @rAcademicId bigint,
	 @rExamId bigint ,
	 @rCoScholasticScopeId int=0,
	 @rBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

DECLARE @lIsCoScholasticGrade	bit,@lIsCoScholasticGradeIndicator bit, @lIsCoScholasticGradeDesIndicator bit  
 
 
SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator  
 
FROM sAssessment.tExamMaster WHERE Id = @rExamId --and coscholasticscopeid=@rCoScholasticScopeId
	SELECT		
			 
			Convert(nvarchar(10),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,	
			Convert(nvarchar(20),@rCoScholasticScopeId) AS   CoScholasticScopeIdText,	
			Convert(nvarchar(20),@rBatchId) AS   BatchIdText,	
		 
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.OrderIndex AS CoSujbectOrderIndex,
			cceCSGM.OrderIndex AS CoSubjectGroupOrderIndex,
			@lIsCoScholasticGrade AS IsCoScholasticGrade,
			@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
			@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
			cceCSGM.CCECSGroupTypeId,
			cceCSGM.Code,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType,
			EM.CoScholasticTitle,
			cceCSS.ConvertedMark,
			cceCSS.ObtianMark,
			cceCSM.OrderIndex,
			CASE WHEN cceCSGM.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			FC.TotalMark
			
	FROM 
			sAssessment.tCCECSExamScore cceCSS		
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamId
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId			 
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id
			INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = EM.ClassId AND cceCSM.Id = FC.CCECSId AND FC.BatchId = @rBatchId
			 
	WHERE 
		     cceCSS.ExamId=@rExamId
		     AND cceCSS.AcademicId=@rAcademicId	
		     AND CCC.BatchID=@rBatchId
		     AND FC.IsOptional = 0
		      
	UNION ALL
	
		SELECT		
			 
			Convert(nvarchar(10),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,	
			Convert(nvarchar(20),@rCoScholasticScopeId) AS   CoScholasticScopeIdText,	
			Convert(nvarchar(20),@rBatchId) AS   BatchIdText,	
		 
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.OrderIndex AS CoSujbectOrderIndex,
			cceCSGM.OrderIndex AS CoSubjectGroupOrderIndex,
			@lIsCoScholasticGrade AS IsCoScholasticGrade,
			@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
			@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
			cceCSGM.CCECSGroupTypeId,
			cceCSGM.Code,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType,
			EM.CoScholasticTitle,
			cceCSS.ConvertedMark,
			cceCSS.ObtianMark,
			cceCSM.OrderIndex,
			CASE WHEN cceCSGM.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			FC.TotalMark
	FROM 
			sAssessment.tCCECSExamScore cceCSS		
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamId
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId			 
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
			INNER JOIN sAssessment.tOptionalCCECS OCS ON OCS.AcademicId = cceCSS.AcademicId AND OCS.CCECSId = cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = EM.ClassId AND cceCSM.Id = FC.CCECSId AND FC.BatchId = @rBatchId
	WHERE 
		     cceCSS.ExamId=@rExamId
		     AND cceCSS.AcademicId=@rAcademicId	
		     AND CCC.BatchID=@rBatchId 
		     AND FC.IsOptional = 1 
		      
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetStandardGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardGet]
	 
	 @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,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @GradeString nvarchar(1000),  @GradeStringRemark nvarchar(500),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

Declare @DecimalConfigid nvarchar(20)='' , @lOrgId int=0
SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster where Id=@rBatchId
SELECT @DecimalConfigid =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @lOrgId
 
	SELECT 
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		ESGM.Title AS Exam,
		StuM.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		R.AcademicId,			
		R.ResultStatus,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,
		R.Percentile,			
		RD.Id AS ResultDetailId,		
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		RD.Obtain AS SubjectObtain,
		ED.Minimum AS SubjectMinimum,
		ED.Maximum AS SubjectMaximum,
		RD.SubjectGrade,
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		R.Id AS ResultId,
		CS.Id AS SubjectId,			 	
		EM.IsMarksInDecimal,
		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsMarksInDecimal,
		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,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END) AS StudentPhoto,
		RD.IsPresent,
		CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,			
		OM.SmallAddress1,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
		
		EM.IsDisplayTeacherSign,
		Em.IsDisplayPrincipalSign,
		(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
		ELSE NULL END)AS EmployeeSign,
		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,
		
		SR.StudentHeight,
		SR.StudentWeight,		
		SR.PresentDays,			
		SR.TotalDays,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.Resultremark3,
		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.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		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(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		BM.Title AS BatchName,
		Em.DecimalFormat,
		RD.GraceMark,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(BGM.Title,'') AS BloodGroup,
		GS.GradeTitle,
		GS.GradePoint,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		RD.KrupaMark,
		RD.Remark AS OtherDetailRemark,
		ISNULL(SO.AdhaarNumber,'') AS AdharNumber,
		ISNULL(SO.UIDNumber,'') AS UIDNumber,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		(CASE  When EM.IsDisplayAbsentCount=1 then ([sAssessment].[fGetAbsentCount](@rExamId,R.AcademicId, CS.Id)) ELSE 0 END) AS AbsentCount,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = 20438 AND OrgId=A.OrgId),0) AS ReportTemplate,
		StuM.SUId As SUID,
		ISNULL(SO.MotherTongue,'') as MotherTongue,
		CONVERT(bit,@DecimalConfigid) AS IsDecimal,
		ISNULL(Stum.RegistrationNumber,'') as RegistrationNumber,
		EM.IsDisplayHighestDivisionMark,
		EM.ResultSheetAdditionalTitle,
		SR.ExamSeatNo,
		ISNULL(R.ResultIndicator,'') AS ResultIndicator
	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
		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
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		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
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
		LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.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 sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
		LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		--AND  ISNULL(EMP.IsOtherUser,0) = 0
		AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		order by A.RollNo,ED.DisplayOrder
END
GO
PRINT N'Altering Procedure [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
 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

Declare @lDecimalConfig nvarchar(20)='', @lOrgId int
SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id=@rBatchId
SELECT @lDecimalConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @lOrgId

DECLARE @lAbsentRemarkConfig nvarchar(20) = ''
SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId


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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(100),
		StudCode NVarchar(20),
		StudentName Nvarchar(300),
		RollNo int,
		ResultStatus Nvarchar(50),	
		ClassName NVarchar(100),		
		Division NVarchar(100),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(5,2),
		RankNumber int,
		ResultGrade NVarchar(10),
		
		MaximumMark1 decimal(10,2),		
		SubjectGrade1 NVarchar(10),
		Obtain1 decimal(5,2) Default 0,
		ExamMaximum1 decimal(10,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(10,2),	
		SubjectGrade2 NVarchar(10),
		Obtain2 decimal(5,2) Default 0,
		ExamMaximum2 decimal(10,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(10,2),
		SubjectGrade3 NVarchar(10),
		Obtain3 decimal(5,2) Default 0,
		ExamMaximum3 decimal(10,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(10,2),	
		SubjectGrade4 NVarchar(10),
		Obtain4 decimal(5,2) Default 0,
		ExamMaximum4 decimal(10,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(10,2),		
		SubjectGrade5 NVarchar(10),
		Obtain5 decimal(5,2) Default 0,
		ExamMaximum5 decimal(10,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(10,2),		
		SubjectGrade6 NVarchar(10),
		Obtain6 decimal(5,2) Default 0,
		ExamMaximum6 decimal(10,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(10,2),		
		SubjectGrade7 NVarchar(10),
		Obtain7 decimal(5,2) Default 0,
		ExamMaximum7 decimal(10,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(10,2),	
		SubjectGrade8 NVarchar(10),
		Obtain8 decimal(5,2) Default 0,
		ExamMaximum8 decimal(10,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(10,2),		
		SubjectGrade9 NVarchar(10),
		Obtain9 decimal(5,2) Default 0,
		ExamMaximum9 decimal(10,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(10,2),		
		SubjectGrade10 NVarchar(10),
		Obtain10 decimal(5,2) Default 0,
		ExamMaximum10 decimal(10,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(10,2),		
		SubjectGrade11 NVarchar(10),
		Obtain11 decimal(5,2) Default 0,
		ExamMaximum11 decimal(10,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(10,2),		
		SubjectGrade12 NVarchar(10),
		Obtain12 decimal(5,2) Default 0,
		ExamMaximum12 decimal(10,2),
		IsPresent12 bit,
		
		MaximumMark13 decimal(10,2),		
		SubjectGrade13 NVarchar(10),
		Obtain13 decimal(5,2) Default 0,
		ExamMaximum13 decimal(10,2),
		IsPresent13 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(10),
		SubjectGradeTerm2 NVarchar(10),
		SubjectGradeTerm3 NVarchar(10),
		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(300),
		Remark3 nvarchar(300),
		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(5,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(10),
		PercentileTerm1 decimal(5,2),
		ResultStatusTerm1 Nvarchar(50),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(5,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(10),
		PercentileTerm2 decimal(5,2),
		ResultStatusTerm2 Nvarchar(50), 
		TotalMarkTerm3 	decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(5,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(10),
		PercentileTerm3 decimal(5,2),
		ResultStatusTerm3 Nvarchar(50), 
		
		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(10),
		SubjectName NVarchar(100),
		SubjectCode Nvarchar(20),	
		SubjectMinimum decimal(10,2),		
		SubjectMaximum decimal(10,2),
		SubjectObtain  decimal(5,2),
		
		Exam1Name Nvarchar(100),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(5,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(10),
		Percentile1 decimal(5,2),
		ResultStatus1 Nvarchar(50),
		Exam1CombineExamName Nvarchar(100),
				
		Exam2Name nvarchar(100),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(5,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(10),
		Percentile2 decimal(5,2),
		ResultStatus2 Nvarchar(50),
		Exam2CombineExamName Nvarchar(100),
		
		Exam3Name nvarchar(100),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(5,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(10),
		Percentile3 decimal(5,2),		
		ResultStatus3 Nvarchar(50),
		Exam3CombineExamName Nvarchar(100),
		
		Exam4Name nvarchar(100),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(5,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(10),
		Percentile4 decimal(5,2),
		ResultStatus4 Nvarchar(50),
		Exam4CombineExamName Nvarchar(100),
		
		Exam5Name nvarchar(100),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(5,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(10),
		Percentile5 decimal(5,2),
		ResultStatus5 Nvarchar(50),
		Exam5CombineExamName Nvarchar(100),
		
		Exam6Name nvarchar(100),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(5,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(10),
		Percentile6 decimal(5,2),
		ResultStatus6 Nvarchar(50),
		Exam6CombineExamName Nvarchar(100),
		
		Exam7Name nvarchar(100),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(5,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(10),
		Percentile7 decimal(5,2),
		ResultStatus7 Nvarchar(50),
		Exam7CombineExamName Nvarchar(100),
		
		Exam8Name nvarchar(100),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(5,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(10),
		Percentile8 decimal(5,2),
		ResultStatus8 Nvarchar(50),
		Exam8CombineExamName Nvarchar(100),
		
		
		Exam9Name nvarchar(100),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(5,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(10),
		Percentile9 decimal(5,2),
		ResultStatus9 Nvarchar(50),
		Exam9CombineExamName Nvarchar(100),
		
		Exam10Name nvarchar(100),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(5,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(10),
		Percentile10 decimal(5,2),
		ResultStatus10 Nvarchar(50),
		Exam10CombineExamName Nvarchar(100),
		
		Exam11Name nvarchar(100),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(5,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(10),
		Percentile11 decimal(5,2),
		ResultStatus11 Nvarchar(50),
		Exam11CombineExamName Nvarchar(100),
		
		Exam12Name nvarchar(100),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(5,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(10),
		Percentile12 decimal(5,2),
		ResultStatus12 Nvarchar(50),
		Exam12CombineExamName Nvarchar(100),

		Exam13Name nvarchar(100),	
		TotalMarks13 decimal(8,2),
		TotalObtain13 decimal(8,2),
		Percentage13 decimal(5,2),
		RankNumber13 int,
		ResultGrade13 NVarchar(10),
		Percentile13 decimal(5,2),
		ResultStatus13 Nvarchar(50),
		Exam13CombineExamName Nvarchar(100),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		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),
		Exam13Code 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(100),
		LastName nvarchar(100),
		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(50),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(100),
		SubjectGroupCode nvarchar(20),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(100),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(5,2),	
		SubjectObtainTerm2 decimal(5,2),
		SubjectObtainTerm3  decimal(5,2),
		SubjectMaxTerm1 decimal(10,2),
		SubjectMaxTerm2 decimal(10,2),
		SubjectMaxTerm3 decimal(10,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(20),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		TotalDays13 decimal(6,2),
		PresentDays13 decimal(6,2),
		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(1000),
		GeneralRemarkTerm2 nvarchar(1000),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(6,2),
		SR_WeightTerm1 decimal(6,2),
		SR_HeightTerm2 decimal(6,2),
		SR_WeightTerm2 decimal(6,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(20),
		UIdNumber nvarchar(50),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(50),
		MotherMail nvarchar(50),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(10),
		StreamTitle nvarchar(50),
		AdmissionNo nvarchar(50),
		AdmissionDate Date,
		MiddleName nvarchar(100) ,
		FatherOccupation nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		IsDecimal bit,
		IsAbsentRemark bit,
		FinalAbsentRemark nvarchar(100),
		AbsentRemark1 nvarchar(100),
		AbsentRemark2 nvarchar(100),
		AbsentRemark3 nvarchar(100),
		AbsentRemark4 nvarchar(100),
		AbsentRemark5 nvarchar(100),
		AbsentRemark6 nvarchar(100),
		AbsentRemark7 nvarchar(100),
		AbsentRemark8 nvarchar(100),
		AbsentRemark9 nvarchar(100),
		AbsentRemark10 nvarchar(100),
		AbsentRemark11 nvarchar(100),
		AbsentRemark12 nvarchar(100),
		AbsentRemark13 nvarchar(100),
		ExamMaximumTerm1 decimal(6,2),
		ExamMaximumTerm2 decimal(6,2),
		ExamMaximumTerm3 decimal(6,2)

		)	
	 --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,
	SUId,
	HighestDivisionMark,
	HighestDivisionGrade,
	StreamTitle,
	AdmissionNo,
	AdmissionDate,
	MiddleName ,
	FatherOccupation,
	ResultSheetAdditionalTitle,
	IsDecimal,
	IsAbsentRemark,
	FinalAbsentRemark
	)
	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,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS 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,
		ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm1,
	    ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm2,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm1,
	    ISNULL(SR.TotalDays,0) 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,
		ISNULL(Stum.SUId,'') AS SUId,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,
		ISNULL(StM.Title,'') AS StreamTitle,
		ISNULL(StuA.AdmissionNumber,0) AS AdmissionNo,
		ISNULL(StuA.AdmissionDate,'') AS AdmissionDate,
		Stum.MiddleName ,
		ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
		ISNULL(EM.ResultSheetAdditionalTitle, '') AS ResultSheetAdditionalTitle,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
		ISNULL(RD.AbsentRemark,'') AS FinalAbsentRemark
				
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
	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.tStreamMaster StM ON CM.StreamId = Stm.Id
	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 AND  ISNULL(EMP.IsOtherUser,0) = 0
	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
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	
	 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 (
	 (@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,	
					 AbsentRemark' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.AbsentRemark,' + CHAR(39)+CHAR(39) + '),
					 		
					 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 AND R.ExamId = ED.ExamId
						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)
		
		Declare @lCombineExamId int
			SELECT @lCombineExamId = EC.ExamId  FROM [sAssessment].[tExamMaster] EM 
										INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId  
										INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId in (SELECT SubExamId  FROM sAssessment.tExamCombine WHERE examid=@rExamId) 
										WHERE   (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId AND EM.Id = @lSubExamId
			--SELECT @lSubCombineExamName
		set @query ='update T set 
					 Exam' + convert(nvarchar(15),@lCount)+ 'CombineExamName =  EM.DisplayTitle
					  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), @lCombineExamId) 
				
				--Print @query		
		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 AND R.ExamId = ED.ExamId
						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,
					ExamMaximumTerm1 = EM.ExamMaximum
					
					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 AND R.ExamId = ED.ExamId
						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,
					ExamMaximumTerm2 = EM.ExamMaximum			
					 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 AND R.ExamId = ED.ExamId
						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,
					ExamMaximumTerm3 = EM.ExamMaximum			
					 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 ,	
 --			'' As FatherOccupation ,
 --			0 AS IsDecimal,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm1,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm2,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm3

 --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 Procedure [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 @DecimalConfid nvarchar(20)=''
SELECT @DecimalConfid =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId


--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,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS 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,
			ISNULL(C.ParentContactNo,'') AS ParentContactNo,
			ISNULL(C.StudentContactNo,'') AS StudentContactNo,
			(C.PresentStreetOne+' '+C.PresentStreetTwo+' '+C.PresentStreetThree+' '+C.PresentCountry+' '+C.PresentState+' '+C.PresentCity+' '+C.PresentZipCode) AS Address1,
			CONVERT(bit,@DecimalConfid) AS IsDecimal,
			--added by megha for 0027299
			AR.ResultGrade As OverallGrade,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS StudentName,
			ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName
			
			--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
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id=DM.InchargeEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 -- Mantis : 28354	
			
		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 Procedure [sAttendance].[pHoliDayCountGet]...';


GO
 
ALTER PROCEDURE [sAttendance].[pHoliDayCountGet]
	
	@rMonth int=0,
	@rYear int=0,
	@rBatchId int=0,
	@rOrgId int=0,
	@rClassId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	CREATE table #Table1 (Id bigint identity,FromDate Date,ToDate Date,DivId int,IsExists bit)
	
	CREATE table #Table2 (Id bigint identity,FromDate Date,ToDate Date,DivId int)
	
	INSERT INTO #Table2 
	SELECT 
	ES.FromDate, 
	ES.ToDate,0
	from sActivity.tEventSchedule ES
	INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleId = ES.Id
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = EA.SourceId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
	Where (MONTH(FromDate)<= @rMonth AND MONTH(ToDate) >= @rMonth) AND ES.IsHoliDay =1 
	AND (YEAR(FromDate)=@rYear AND YEAR(ToDate) = @rYear)
	AND EA.SourceTypeId = 2005 AND CM.Id = @rClassId
	AND ((ES.BatchId = @rBatchId)OR(@rBatchId=0))
	GROUP BY ES.FromDate,ES.ToDate
	  
	INSERT INTO #Table1 
	select FromDate,ToDate,Max(DivId),0
	from
	( 
	SELECT case when MONTH(FromDate)=@rMonth then FromDate
				when MONTH(FromDate)<>@rMonth and MONTH(ToDate)=@rMonth then DATEADD(DD,-Day(ToDate)+1,ToDate)
				when MONTH(FromDate)<@rMonth and MONTH(ToDate)>@rMonth then cast(rtrim(@rYear *10000+ @rMonth *100+ 01) as date) --mantis:28433
				else FromDate end as FromDate,
				ToDate,
				DivId	
	From #Table2
	GROUP BY  FromDate,ToDate,DivId
	)As Tmp
	GROUP BY  Tmp.FromDate,Tmp.ToDate,Tmp.DivId
	
	DECLARE @lTempCount int=0
	SELECT @lTempCount = count(Id) from #Table1
	WHILE @lTempCount > 0 
	BEGIN
		DECLARE @lFromDate Date,@lToDate Date

		SELECT @lFromDate = FromDate, @lToDate = ToDate FROM #Table1 WHERE Id=@lTempCount
		IF EXISTS(SELECT 1 FROM #Table1 WHERE Id <> @lTempCount AND ((@lFromDate between FromDate and ToDate) AND (@lToDate between FromDate and ToDate)))
		BEGIN
			UPDATE #Table1 SET IsExists = 1 WHERE Id = @lTempCount	
		END
		SET @lTempCount = @lTempCount - 1
	END

	 
	DECLARE @lCount int
	SELECT @lCount = count(Id) from #Table1
	DECLARE @lStatus nvarchar(5),@lFromYear int,@lFromMonth int,@lFromDay int,@lDivision int,@lToYear int,@lToMonth int,@lToDay int
	DECLARE @lHoliDayCount int,@lBeginCount int ,@lEndCount int , @lTotalMonth int 
	SET @lHoliDayCount =0
	
		WHILE @lCount > 0 
					BEGIN
						SELECT
							@lFromYear = YEAR(FromDate),
							@lFromMonth = MONTH(FromDate),
							@lFromDay = DAY(FromDate),
							@lToYear = YEAR(ToDate),
							@lToMonth = MONTH(ToDate),
							@lToDay = DAY(ToDate),
							@lDivision = DivId,
							@lBeginCount = DAY(FromDate),
							@lEndCount = DAY(ToDate)
						FROM #Table1 T WHERE Id = @lCount AND IsExists = 0
					
						IF(@lFromDay = @lToDay  AND @lFromMonth = @lToMonth)
						BEGIN
							
							SELECT @lStatus = [sAttendance].[fWeekHOffGet]
							(@lFromYear,@lFromMonth,@lFromDay,@rBatchId,@rClassId,@lDivision,'',@rOrgId)
							IF(@lStatus = 'H')SET @lHoliDayCount=@lHoliDayCount+1
							
							
						END
						ELSE IF(@lFromDay != @lToDay)
						BEGIN
							IF(@lFromMonth = @lToMonth)
							BEGIN
								WHILE (@lBeginCount <= @lEndCount)
								BEGIN
								  
									SELECT @lStatus = [sAttendance].[fWeekHOffGet] 	(@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rClassId,@lDivision,'',@rOrgId)
									IF(@lStatus = 'H')
										SET @lHoliDayCount=@lHoliDayCount+1
									
									SET @lBeginCount = @lBeginCount +1	
							   END
							END
							ELSE
							BEGIN
								SET @lTotalMonth = @lToMonth - @lFromMonth
								 WHILE (@lTotalMonth > 0 AND @rMonth=@lFromMonth)
								 BEGIN
									 DECLARE @lDays int = 0
									 SELECT @lDays = sCommon.fGetDaysInMonth(@lFromMonth,@lFromYear)
									 WHILE (@lBeginCount  <= @lDays)
									 BEGIN
										
										SELECT @lStatus = [sAttendance].[fWeekHOffGet] 	(@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rClassId,@lDivision,'',@rOrgId)
										IF(@lStatus = 'H')
											SET @lHoliDayCount=@lHoliDayCount+1
											
										SET @lBeginCount = @lBeginCount +1
									END
									SET @lTotalMonth = @lTotalMonth-1
								 END
							END
						END
						SET @lCount = @lCount - 1
					END
	SELECT @lHoliDayCount
	DROP TABLE #Table1
	DROP TABLE #Table2
END
GO
PRINT N'Altering Procedure [sAttendance].[pRptStudentRegisterSubjectWiseGet]...';


GO

ALTER PROCEDURE [sAttendance].[pRptStudentRegisterSubjectWiseGet]
	 	 	  
		 @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 = 0,
		 @rDepartmentId int,
		 @rPeriodNo int,
		 @rStatusId int=0,
		 @rAttendanceGroupId int = 0,
		 @rFilter int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rToDate = DATEADD (d,1,@rToDate)

IF @rFilter = 1
	BEGIN
		Select 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.AcademicId,
		SA.Name,
		SA.Code,
		SA.RollNo,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		R.AttendanceDate,
		ISNULL(SM.Id,0) AS SubjectId,
		ISNULL(SM.Code,'') AS SubjectCode,
		ISNULL(SM.Title,'') AS SubjectName,
		R.IsPresent,
		R.PeriodNo,
		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 (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 (SR.IsPresent = 0)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalAbsentCount,
		ISNULL(AG.Id,0) AS AttendanceGroupId,
		ISNULL(AG.Title,'') AS AttendanceGroupTitle,
		@rFilter AS Filter
		
	From 
	sAttendance.tStudentRegister R	 
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=R.SubjectId
	LEFT JOIN sAttendance.tAttendanceGroup AG ON AG.Id = R.AttendanceGroupId
	WHERE
		((R.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 ((R.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((R.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND R.AttendanceTypeId = 5
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((R.PeriodNo=@rPeriodNo) OR (@rPeriodNo=0))
		AND ((SA.StatusId =@rStatusId ) OR (@rStatusId=0))

		ORDER BY SA.AcademicId, SM.OrderIndex
	END

ELSE
	BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.AcademicId,
		SA.Name,
		SA.Code,
		SA.RollNo,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		R.AttendanceDate,
		ISNULL(SM.Id,0) AS SubjectId,
		ISNULL(SM.Code,'') AS SubjectCode,
		ISNULL(SM.Title,'') AS SubjectName,
		R.IsPresent,
		R.PeriodNo,
		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 (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 (SR.IsPresent = 0)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalAbsentCount,
		ISNULL(AG.Id,0) AS AttendanceGroupId,
		ISNULL(AG.Title,'') AS AttendanceGroupTitle,
		@rFilter AS Filter
		
	FROM 
	sAttendance.tStudentRegister R	 
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=R.SubjectId
	INNER JOIN sAttendance.tAttendanceGroup AG ON AG.Id = R.AttendanceGroupId
	WHERE
		((R.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 ((R.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((R.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND R.AttendanceTypeId = 5
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((R.PeriodNo=@rPeriodNo) OR (@rPeriodNo=0))
		AND ((SA.StatusId =@rStatusId ) OR (@rStatusId=0))
		AND ((R.AttendanceGroupId = @rAttendanceGroupId ) OR (@rAttendanceGroupId=0))

		ORDER BY SA.AcademicId, SM.OrderIndex
	END

END
GO
PRINT N'Altering Procedure [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,
	 @rUserId bigint = 0,
	 @rIsDetail bit=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) + ') 
											 When D'+ convert(nvarchar(15),@lDay) +' =''XX'' AND  (Cast(''' + convert(nvarchar(15),@lDate) + ''' as date)<GETDATE()) And (cast(ED.DateOfJoining as date)<= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfJoining,'''')='''')AND (ED.DateOfleaving>= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfleaving,'''')='''')  then ''A''
											 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
	
	CREATE TABLE #TempMonthTransWitIoOutTime (EmployeeId bigint,Attn_Date DateTime,InTime nvarchar(20),OutTime nvarchar(20))
	if(@rIsDetail=1)
	BEGIN
	--mantis:28452 Start
		WITH CloudTransactionDataEntries AS (
		SELECT 
			SourceId,Attn_Dt,
			CONVERT(VARCHAR(10), In_Out_Time, 108) as In_Out_Time,
			ROW_NUMBER() OVER (PARTITION BY SourceId ORDER BY CONVERT(VARCHAR(10), In_Out_Time, 108)) AS In_Out_Time_number
		FROM 
			[sBiometric].[tCloudTransactionData]

		WHERE 
			SourceTypeid=95
				AND Attn_Dt>=@rFromDate
				AND Attn_Dt<=@rToDate
		)
		INSERT INTO #TempMonthTransWitIoOutTime
		SELECT 
			e1.SourceId,
			e1.Attn_Dt,
			e1.In_Out_Time AS in_time,
			e2.In_Out_Time AS out_time
		FROM 
			CloudTransactionDataEntries e1
		JOIN 
			CloudTransactionDataEntries e2 
		ON 
			e1.SourceId = e2.SourceId 
			AND e1.In_Out_Time_number = e2.In_Out_Time_number - 1
			ANd  e1.In_Out_Time_number%2=1
			AND e1.Attn_Dt=e2.Attn_Dt
		ORDER BY 
			e1.SourceId,e1.Attn_Dt, e1.In_Out_Time
	--INSERT INTO #TempMonthTransWitIoOutTime
	--	SELECT  SourceId,Attn_Dt,CONVERT(VARCHAR(10), I.In_Out_Time, 108),CONVERT(VARCHAR(10), O.In_Out_Time, 108)
	--       FROM [sBiometric].[tCloudTransactionData] I
	--	OUTER APPLY (
	--					SELECT TOP 1    In_Out_Time,
	--									Mode
	--					FROM [sBiometric].[tCloudTransactionData] t
	--					WHERE       t.SourceId = I.SourceId
	--							AND t.In_Out_Time > I.In_Out_Time
	--							AND SourceTypeid=95
	--							AND t.Attn_Dt =I.Attn_Dt
	--							AND Mode = 'OUT'
	--					ORDER BY t.In_Out_Time
	--				) O
	--	WHERE I.Mode = 'IN'
	--	AND SourceTypeid=95
	--	AND I.Attn_Dt>=@rFromDate
	--	AND I.Attn_Dt<=@rToDate
	--mantis:28452 End
	--	--select * from #TempMonthTransWitIoOutTime
	END
	--Select * from #TempMonthTrans
	--return
	
	IF(@rStatus = '(0)')
	BEGIN
		SET @strQuery = 'select Day(T.Attn_Date), T.*,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	convert(nvarchar(20),Emp.Code) AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,''' +CAST(@rOrderBy AS NVARCHAR(3)) + ''' AS OrderBy,
	DM.Title AS DeptName, Emp.Number AS Number,	OM.Id AS OrgId, OM.Title AS OrganizationTitle,CTD.*,'+Cast(@rIsDetail AS NVARCHAR(10))+' AS IsDetail
	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.vDepartment DM ON DM.Id = ED.OrganizationDepartmentId
	LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId 	
	Left Join #TempMonthTransWitIoOutTime CTD ON  CTD.EmployeeId=T.EmployeeId AND CTD.Attn_Date=T.Attn_Date  	
	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 (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') AND DM.UserId = ' + convert(nvarchar(15),@rUserId) + ' Order By T.Attn_Date,T.EmployeeId'
	END
	ELSE
	BEGIN
	SET @strQuery = 'select Day(T.Attn_Date), T.*,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	convert(nvarchar(20),Emp.Code) AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,''' +CAST(@rOrderBy AS NVARCHAR(3)) + ''' AS OrderBy,
	DM.Title AS DeptName, Emp.Number AS Number,	OM.Id AS OrgId, OM.Title AS OrganizationTitle,CTD.*,'+Cast(@rIsDetail AS NVARCHAR(10))+' AS IsDetail
	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.vDepartment DM ON DM.Id = ED.OrganizationDepartmentId
	LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId 
	Left Join #TempMonthTransWitIoOutTime CTD ON  CTD.EmployeeId=T.EmployeeId AND CTD.Attn_Date=T.Attn_Date
	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) + ') AND DM.UserId = ' + convert(nvarchar(15),@rUserId) + ' Order By T.Attn_Date,T.EmployeeId'	
	END
	--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,
	--@rIsDetail AS IsDetail,
	--'' 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,
	--'' AS OutTime,
	--'' as InTime
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 Procedure [sBiometric].[pBiometricEmployeeAttendanceGet]...';


GO

ALTER PROCEDURE [sBiometric].[pBiometricEmployeeAttendanceGet]
	 	 
	 	 @rDepartmentId int=0,
	 	 @rAttendanceDate date='',
	 	 @rCode nvarchar(20)='',
	 	 @rBatchId int=0,
	 	 @rOrgId int=0,
		 @TimeSheetStatusId nvarchar(10) = '0'
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

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)
  BEGIN
	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@rAttendanceDate) AS varchar(2)), 2)
	Select @lMonth = RIGHT('00' + CAST(DATEPART(MM,@rAttendanceDate) AS varchar(2)), 2)
	Select @lYear  = RIGHT('0000' + CAST(DATEPART(yyyy,@rAttendanceDate) AS varchar(4)), 4)
	
	
	
		set @strQuery ='Select EM.EmployeeId,EM.Code AS EmployeeCode,EM.EmployeeName,EM.DepartmentName,ISNULL(EAR.IsPresent,''true'') as IsPresent,
			ISNULL(EAR.AbsentReasonId,0) as AbsentReasonId,CASE WHEN EAR.UpdatedUserId IS NULL THEN cast(0 as bit) ELSE cast(1 as bit) END AS IsDeleted,
			ISNULL(EAR.AttendanceTagId,0) AS AttendanceTagId,ISNULL(EAR.LeaveTypeId,0) AS LeaveTypeId,ISNULL(EAR.LeavePeriodId,0) AS LeavePeriodId,
			ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') AS FirstIn,ISNULL(D'+convert(nvarchar(15),@lDay)+'_Out,''00:00'') AS LastOut,ISNULL(D'+convert(nvarchar(15),@lDay)+'_L,''00:00'') AS LateBy,ISNULL(D'+convert(nvarchar(15),@lDay)+'_E,''00:00'') AS EarlyBy, ISNULL(D'+convert(nvarchar(15),@lDay)+'_T,''00:00'') AS Duration,
			ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'') AS OldPresentStatus,
			CASE When (([sHrm].[fWeekHOffGetBio](EM.EmployeeId, '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''H'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''PH''
			 When (([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''H'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')=''00:00'')) THEN ''H''  
			 When (([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''PW''
			 When (([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') =''00:00''))  then ''W''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''W'')AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )!=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''P''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''PW'')AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )!=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''P''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''W'')AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )!=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') =''00:00''))  then ''A''
			 WHEN ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00'')) THEN ''PW''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''XX'')AND (Cast('''+convert(nvarchar(15),@rAttendanceDate)+''' as date)<GETDATE()) And (cast(EM.DateOfJoining as date)<= Cast('''+convert(nvarchar(15),@rAttendanceDate)+''' as date) OR ISNULL(EM.DateOfJoining,'''')='''')AND (EM.DateOfleaving>= Cast('''+convert(nvarchar(15),@rAttendanceDate)+''' as date) OR ISNULL(EM.DateOfleaving,'''')='''') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') =''00:00''))  then ''A''
			 ELSE
			 ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'') END as PresentStatus
			 From 
		sHrm.vExtEmployeeMaster EM 
		LEFT JOIN sBiometric.tMonthTrans T1 ON EM.EmployeeId = T1.EmployeeId AND (ISNULL(T1.SourceTypeId,95) = 95 OR SourceTypeId = 0) AND ATTN_DT = cast(rtrim(YEAR(''' + convert(nvarchar(15),@rAttendanceDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@rAttendanceDate) + ''') *100+ 01) as datetime)
		LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId=EM.EmployeeId AND EAR.AttendanceDate ='''+convert(nvarchar(15),@rAttendanceDate)+'''  AND (EAR.BatchId ='+convert(nvarchar(15), @rBatchId)+')
		WHERE 
			 ((EM.DepartmentId='+convert(nvarchar(15),@rDepartmentId)+') OR ('+convert(nvarchar(15),@rDepartmentId)+'=0))
		  AND ((EM.Code like '''+convert(nvarchar(15),@rCode)+''' ) OR (ISNULL('''+convert(nvarchar(15),@rCode)+''','''')=''''))
		  AND (EM.OrgId = '+convert(nvarchar(15),@rOrgId)+')
		  AND ((EM.DateOfleaving >= '''+convert(nvarchar(15),@rAttendanceDate)+''' ) OR ISNULL(EM.DateOfleaving,'''') = '''')
          AND ((EM.DateOfJoining <='''+convert(nvarchar(15),@rAttendanceDate)+''' ) OR ISNULL(EM.DateOfJoining,'''') = '''') 
		  AND (EM.StatusId = 7)
		  AND (EM.IsOtherUser = 0)
		  AND  (( '''+convert(nvarchar(15),@TimeSheetStatusId)+''' = ''1'' AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_T,''00:00'') < ''09:30'')) OR ( '''+convert(nvarchar(15),@TimeSheetStatusId)+'''  != ''1'' AND ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'') = '''+convert(nvarchar(15),@TimeSheetStatusId)+'''  OR '''+convert(nvarchar(15),@TimeSheetStatusId)+''' =''0''))))
          ORDER BY EM.Number'
	--print @strQuery
	execute (@strQuery )
	--print @strQuery
  END
END
GO
PRINT N'Altering Procedure [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,
	 @OrgGroupDepartmentId 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 
AND ((ED.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=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) + ')
		PRINT(@weekoffstatus)

		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 +''' 
						When D'+ convert(nvarchar(15),@lDay) +' =''XX'' AND  (Cast(''' + convert(nvarchar(15),@lDate) + ''' as date)<GETDATE()) And (cast(ED.DateOfJoining as date)<= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfJoining,'''')='''')AND (ED.DateOfleaving>= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfleaving,'''')='''')  then ''A''
						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 ) AND (ED.OrgGroupDepartmentId ='''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+'''= 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 Procedure [sBiometric].[pCloudTransactionDataAdd]...';


GO
ALTER PROCEDURE [sBiometric].[pCloudTransactionDataAdd]

@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(
		TransactionId bigint NOT NULL,
		[PunchId] [nvarchar](50) NOT NULL,
		TransactionDateTime [datetime] NOT NULL,
		[DeviceIP] [nvarchar](20) NOT NULL,
		[Mode] [nvarchar](10) NOT NULL,
		[CreatedDateTime] [datetime] NOT NULL
	)
	INSERT INTO #tTable
	SELECT 
		A.TransactionId,
		A.PunchId,
		A.TransactionDateTime,
		A.DeviceIP,
		A.Mode,
		sCommon.fGetDate()
	FROM OPENXML (@intDoc, '/Table/CloudTransactionData', 1)
	WITH
	(
		TransactionId bigint '@TransactionId',
		PunchId nvarchar(50) '@PunchId',
		TransactionDateTime datetime '@TransactionDateTime',
		DeviceIP nvarchar(20) '@DeviceIP',		
		Mode nvarchar(10) '@Mode'	
	) A	

	INSERT INTO sBiometric.tCloudTransactionRawData
	SELECT 
		A.TransactionId,
		A.PunchId,
		A.TransactionDateTime,
		A.DeviceIP,
		A.Mode,
		A.CreatedDateTime
	From #tTable A 
	Where NOT EXISTS 
		(SELECT 1 FROM  sBiometric.tCloudTransactionRawData CRD where  A.TransactionDateTime=CRD.TransactionDateTime AND A.PunchId=CRD.PunchId AND A.DeviceIP=CRD.DeviceIP)
	
	INSERT INTO [sBiometric].[tCloudTransactionData] with (rowlock)
	--Employee
	SELECT 
		EM.Id,
		CRD.TransactionDateTime,
		CASE WHEN (SELECT 1 FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = EM.Id AND SourceTypeId = 95) IS NOT NULL THEN 
		(SELECT top 1 ShiftCode FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = EM.Id AND SourceTypeId = 95 order by fromShiftDate desc)
		ELSE EM.ShiftId END AS ShiftCode,
		CONVERT(DATE,CRD.TransactionDateTime) AS Attn_Dt,
		CASE WHEN (SELECT TOP 1 ISNULL(Mode,'IN') FROM [sBiometric].[tCloudTransactionData] WHERE SourceId = EM.Id AND Attn_Dt = CONVERT(DATE,CRD.TransactionDateTime) ORDER BY In_Out_Time DESC) = 'IN' THEN 'OUT' ELSE 'IN' END AS Mode,
		sCommon.fGetDate(),
		CRD.DeviceIP,
		0,
		CRD.PunchId,
		CRD.TransactionId,
		95,
		0
	FROM 
		sBiometric.tCloudTransactionRawData CRD 		
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.PunchId = CRD.PunchId
	WHERE
		CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData)

	UNION ALL

	--Student
	SELECT 
		SM.Id,
		CRD.TransactionDateTime,
		CASE WHEN (SELECT 1 FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = SM.Id AND SourceTypeId = 2003) IS NOT NULL THEN 
		(SELECT top 1 ShiftCode FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = SM.Id AND SourceTypeId = 2003 order by fromShiftDate desc)
		ELSE SM.ShiftId END AS ShiftCode,
		CONVERT(DATE,CRD.TransactionDateTime) AS Attn_Dt,
		CASE WHEN (SELECT TOP 1 ISNULL(Mode,'IN') FROM [sBiometric].[tCloudTransactionData] WHERE SourceId = SM.Id AND Attn_Dt = CONVERT(DATE,CRD.TransactionDateTime) ORDER BY In_Out_Time DESC) = 'IN' THEN 'OUT' ELSE 'IN' END AS Mode,
		sCommon.fGetDate(),
		CRD.DeviceIP,
		0,
		CRD.PunchId,
		CRD.TransactionId,
		2003,
		0
	FROM 
		sBiometric.tCloudTransactionRawData CRD 		
		INNER JOIN sStudent.tStudentMaster SM ON SM.PunchId = CRD.PunchId
	WHERE
		CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData)

	DROP TABLE #tTable
	COMMIT TRANSACTION
	SELECT 1 AS Result
END
GO
PRINT N'Altering Procedure [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,
	 @OrgGroupDepartmentId 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 
AND ((ED.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=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 +''' in (''H'') AND D'+convert(nvarchar(15),@lDay)+'_IN != ''00:00'' then ''PH''
						When ''' +@weekoffstatus +''' in (''W'')  AND D'+convert(nvarchar(15),@lDay)+'_IN != ''00:00'' then ''PW''
						When ''' +@weekoffstatus +''' in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' = ''PW'' AND D'+convert(nvarchar(15),@lDay)+'_IN = ''00:00'' then ''W''
						When ''' +@weekoffstatus +''' not in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' = ''PW'' then ''P''
						When ''' +@weekoffstatus +''' not in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' = ''W'' AND D'+convert(nvarchar(15),@lDay)+'_IN != ''00:00'' then ''P''
						When ''' +@weekoffstatus +''' not in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' =''W'' AND D'+convert(nvarchar(15),@lDay)+'_IN = ''00:00'' then ''A''
						When ''' +@weekoffstatus +''' Not in (''-'',''XX'') 
						Then ''' +@weekoffstatus +''' 
						When D'+ convert(nvarchar(15),@lDay) +' =''XX'' AND  (Cast(''' + convert(nvarchar(15),@lDate) + ''' as date)<GETDATE()) And (cast(ED.DateOfJoining as date)<= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfJoining,'''')='''')AND (ED.DateOfleaving>= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfleaving,'''')='''')  then ''A''
						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 )AND (ED.OrgGroupDepartmentId ='''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+'''= 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)'				
		--print @lQuery				
		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

	--add builders in this for 27928 mantis
	SET @strQuery = 'select '''+@rBuilder1+''' AS Builder1, '''+@rBuilder2+''' AS Builder2, Day(T.Attn_Date), T.*,isnull(A.TotAbsent,0) AS TotAbsent,isnull(TotPresent,0) AS TotPresent,A1.TotWeekOff,isnull(A6.TotEarly,0) as TotEarly,
	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) )' 
	--print @strQuery
	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 Procedure [sBiometric].[pRptEmployeeWiseMonthlySummaryGet]...';


GO

ALTER PROCEDURE [sBiometric].[pRptEmployeeWiseMonthlySummaryGet] 
     @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int ,
	@rDeptId int ,
	@rForYear int,
	@rForMonth int,	 
	@rEmployeeStatusId int,
	@rEmployeeId bigint,
	@rOrgGroupId int
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
  
declare @Days int
Declare @lFromDate datetime
Declare @lToDate datetime


CREATE TABLE #TempMonthTrans  
 (  
 Id int ,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 LateBy nvarchar(20),   
 EarlyBy nvarchar(20), 
 ) 
 select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
 set @lFromDate=CONVERT(nvarchar(20), @rForYear)+ '-' +  CONVERT(nvarchar(20), @rForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @lToDate=CONVERT(nvarchar(20), @rForYear)+ '-' +  CONVERT(nvarchar(20), @rForMonth) + '-' + CONVERT(nvarchar(20), @Days)
 --select @lFromDate,@lToDate
  INSERT INTO #TempMonthTrans 
  select Id,EmployeeId ,Attn_Date,PresentStatus ,LateBy, EarlyBy 
   from [sBiometric].[fBiometricTempMonthTransGet](@rOrgId ,@rDeptId ,@lFromDate,@lToDate,@rEmployeeId)

  SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		MT.EmployeeId,
		MT.EmpCode,
		EM.FirstName + ' ' + EM.LastName AS EmployeeName,  
		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,
		MT.Count_Late AS Count_Late,
		isnull(Absent.TotAbsent,0.00) AS TotalAbsentDays,
		isnull(WeekOff.TotWeekOff,0.00) AS TotalWeekOffs,
		isnull(Holidays.TotHoliday,0.00) AS TotalHolidays,
		isnull(Present.TotPresent,0.00) AS TotalPresentDays,
		isnull(HalfDay.TotHalfDay,0.00) AS TotalHalfDays,
		isnull(ErrorCase.TotalErrorCase,0.00) AS TotalErrorCase,
		ISNULL(EA.PaidLeave,0.00)  as PaidLeave,
		Isnull(EA.LWP,0.00)  AS UnPaidLeave,
		IsNull(MT.TotalHour,'00:00') as TotalHour,
		Isnull(MT.Tot_Early,'00:00') as Tot_Early,
		Isnull(MT.Tot_OT,'00:00') as Tot_OT,
		Isnull(MT.Tot_Late,'00:00') as Tot_Late,
		DM.Displaytitle AS DeptName,
		DM.Id As DeptId
	FROM
	sBiometric.tMonthTrans MT
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId AND (SourceTypeId = 95 OR SourceTypeId=0)
	left join [sHrm].[tEmployeeAttendance] EA ON EA.EmployeeId=Mt.EmployeeId AND EA.ForYear=@rForYear AND EA.ForMonth=@rForMonth
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
	LEFT Join (Select COUNT(*) AS TotPresent,EmployeeId from #TempMonthTrans Where PresentStatus IN ('P','PW','PH') group by EmployeeId) Present ON Present.EmployeeId = MT.employeeID
	LEFT Join (Select COUNT(*) AS TotAbsent,EmployeeId from #TempMonthTrans Where PresentStatus Like 'A' group by EmployeeId) Absent ON Absent.EmployeeId = MT.employeeID
	LEFT Join (Select COUNT(*) AS TotWeekOff,EmployeeId from #TempMonthTrans Where PresentStatus IN ('W','PW','PHW') group by EmployeeId) WeekOff ON WeekOff.EmployeeId = MT.employeeID
	LEFT Join (Select COUNT(*) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like 'HD' group by EmployeeId) HalfDay ON HalfDay.EmployeeId = MT.employeeID
    LEFT Join (Select COUNT(*) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like 'H' group by EmployeeId) Holidays ON Holidays.EmployeeId = MT.employeeID	
	LEFT Join (Select COUNT(*) AS TotalErrorCase,EmployeeId from #TempMonthTrans Where PresentStatus Like 'E' group by EmployeeId) ErrorCase ON ErrorCase.EmployeeId = MT.employeeID	

	WHERE
	(EM.OrgId = @rOrgId OR @rOrgId = 0)
	--AND YEAR(MT.Attn_Dt) = @rForYear
	--AND (MONTH(MT.Attn_dt) = @rForMonth )
	AND MT.Attn_dt=cast(rtrim(@rForYear *10000+ @rForMonth *100+ 01) as datetime) --Mantis Id : 0028180
	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)
	order by MT.EmpCode

	DROP Table #TempMonthTrans	
 --select 
 --@rBuilder1 AS Builder1,
	--	@rBuilder2 AS Builder2,
	--	CAST(0 AS bigint) AS EmployeeId,
	--	0 AS EmpCode,
	--	'' AS EmployeeName,  
	--	0 AS OrganizationId,
	--	'' AS OrganizationTitle,
	--	0 AS OrganizationOrderIndex,
	--	CAST(0 AS bigint) AS EmployeeNumber,
	--	DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays,
	--	0.00 AS Count_Late,
	--	0.00 AS TotalAbsentDays,
	--	0.00 AS TotalWeekOffs,
	--	0.00 AS TotalHolidays,
	--	0.00 AS TotalPresentDays,
	--	0.00 AS TotalHalfDays,
	--	0.00 AS TotalErrorCase,
	--	0.00  as PaidLeave,
	--	0.00  AS UnPaidLeave,
	--	'00:00' as TotalHour,
	--	'00:00' as Tot_Early,
	--	'00:00' as Tot_OT,
	--	'00:00' as Tot_Late,
	--	'' AS DeptName,
	--	0 As DeptId

end
GO
PRINT N'Altering Procedure [sBiometric].[pRptEmployeeWiseStatusSummary]...';


GO
 
 
 
 
 
ALTER PROCEDURE [sBiometric].[pRptEmployeeWiseStatusSummary]
	 @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,
	 @rEmployeeStatusId int=0,
	 @rOrgGroupId int = 0,
	 @OrgGroupDepartmentId int = 0
AS
BEGIN
	SET NOCOUNT ON;
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 
AND ((ED.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=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),
		--OverTime nvarchar(20),EarlyBy nvarchar(20), LateBy nvarchar(20),Duration nvarchar(20))
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](@lEmployeeId,Year(@lDate)  ,Month(@lDate), @lDay, @lBatchId,@lEmpDepartmentID,@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)+'_O,D'+convert(nvarchar(15),@lDay)+'_E,D'+convert(nvarchar(15),@lDay)+'_L,D'+convert(nvarchar(15),@lDay)+'_T 
						----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 )AND (ED.OrgGroupDepartmentId ='''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+'''= 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)'				

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 +''' 
						When D'+ convert(nvarchar(15),@lDay) +' =''XX'' AND  (Cast(''' + convert(nvarchar(15),@lDate) + ''' as date)<GETDATE()) And (cast(ED.DateOfJoining as date)<= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfJoining,'''')='''')AND (ED.DateOfleaving>= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfleaving,'''')='''')  then ''A''
						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 )AND (ED.OrgGroupDepartmentId ='''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+'''= 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 T

	--SELECT  EmployeeId,COUNT(PresentStatus) AS TotPresent FROM #TempMonthTrans WHERE PresentStatus IN ('P','PH','PW') GROUP BY EmployeeId 
			--(SELECT COUNT(PresentStatus) FROM #TempMonthTrans WHERE PresentStatus IN ('A') GROUP BY EmployeeId) AS TotAbsent			

	--SET @strQuery = 'select  Day(T.Attn_Date), T.EmployeeId, T.Attn_Date, SUM(convert(int, left(T.OverTime, 2))+0) AS TotHoursOverTime, SUM(convert(int, substring(T.OverTime, 4,2))+0) AS TotMinutesOverTime, SUM(convert(int, left(T.EarlyBy, 2))+0) AS TotHoursEarlyBy, SUM(convert(int, substring(T.EarlyBy, 4,2))+0) AS TotMinutesEarlyBy,SUM(convert(int, left(T.LateBy, 2))+0) AS TotHoursLateBy, SUM(convert(int, substring(T.LateBy, 4,2))+0) AS TotMinutesLateBy, SUM(convert(int, left(T.Duration, 2))+0) AS TotHoursDuration, SUM(convert(int, substring(T.Duration, 4,2))) AS TotMinutesDuration,
	--isnull(A4.TotPresent,0) AS TotPresent, isnull(A.TotAbsent,0) AS TotAbsent, isnull(A1.TotWeekOff,0) AS TotWeekOff, isnull(TotHalfDay,0) AS TotHalfDay,Isnull(TotHoliday,0) AS TotHoliday,
	--isnull(CLLeave,0) AS CLLeave,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	--Emp.Code AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,
	--DM.Displaytitle DeptName,
	--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,PresentStatus) A1 ON A1.EmployeeId = T.employeeID
	--LEFT Join (Select COUNT(*) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like ''HD'' group by EmployeeId,PresentStatus) A3 ON A3.EmployeeId = T.employeeID
 --   LEFT Join (Select COUNT(*) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like ''H'' group by EmployeeId,PresentStatus) A5 ON A5.EmployeeId = T.employeeID


	--LEFT Join (Select sum(NoOfLeave) AS CLLeave,EmployeeId,LT.Code as LeaveCode from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId 
	--Where FromDate>=''' + Convert(nvarchar(12),@rFromDate) + ''' AND FromDate<=''' + Convert(nvarchar(12),@rToDate) + ''' GRoup By EmployeeId,LT.Code ) AS LV ON LV.EmployeeId = T.EmployeeId

	--LEFT Join (select   distinct  EmployeeId,
 --   ISNULL( stuff((
 --       select Distinct '','' + LT.Code + '':'' + Convert(nvarchar(10),Sum(NoOfLeave)) 
 --       from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
 --       where  (FromDate >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''')) 
 --       AND (ToDate <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
 --       AND L.EmployeeId = L1.EmployeeId AND L.StatusId= 550
 --       group by LT.Code
 --       for xml path('''')
 --   ),1,1,''''),'''') as LeaveCode1
	--from shrm.tLeave L1 
	--inner join shrm.tLeaveTypeMaster LT ON LT.Id=L1.LeaveTypeId AND L1.StatusId=550
	--group by EmployeeId,LT.Code) AS LV1 ON LV1.EmployeeId = T.EmployeeId 
	--WHERE (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0)
 --   AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') 
	--AND (T.Attn_Date >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''') )
	--AND (T.Attn_Date <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
	--GROUP BY T.EmployeeId, DM.Displaytitle, OM.Id, OM.Title, LV.CLLeave, LV.LeaveCode, LV1.LeaveCode1, Emp.Code, Emp.FirstName, Emp.MiddleName, Emp.LastName, T.Attn_Date
	--' 

	SET @strQuery = 'select  Day(T.Attn_Date), T.EmployeeId, T.Attn_Date, SUM(convert(int, left(T.OverTime, 2))) AS TotHoursOverTime, SUM(convert(int, substring(T.OverTime, 4,2))) AS TotMinutesOverTime, SUM(convert(int, left(T.EarlyBy, 2))) AS TotHoursEarlyBy, SUM(convert(int, substring(T.EarlyBy, 4,2))) AS TotMinutesEarlyBy,SUM(convert(int, left(T.LateBy, 2))) AS TotHoursLateBy, SUM(convert(int, substring(T.LateBy, 4,2))) AS TotMinutesLateBy, SUM(convert(int, left(T.Duration, 2))) AS TotHoursDuration, SUM(convert(int, substring(T.Duration, 4,2))) AS TotMinutesDuration,
	isnull(A13.TotPresent,0) AS TotPresent, isnull(A.TotAbsent,0) AS TotAbsent, isnull(A1.TotWeekOff,0) AS TotWeekOff, isnull(TotHalfDay,0) AS TotHalfDay,Isnull(TotHoliday,0) AS TotHoliday,Isnull(TotLateHours,0) AS TotLateHours,
	Emp.Code AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,
	DM.Displaytitle DeptName,
	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
	LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Emp.Id
	LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID
	
	LEFT Join (Select COUNT(PresentStatus) AS TotPresent,EmployeeId from #TempMonthTrans Where PresentStatus IN (''P'',''PH'',''PW'')  group by EmployeeId) A13 ON A13.EmployeeId = T.employeeID 
	LEFT Join (Select COUNT(PresentStatus) AS TotAbsent,EmployeeId from #TempMonthTrans Where PresentStatus Like ''A'' group by EmployeeId) A ON A.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(PresentStatus) AS TotWeekOff,EmployeeId from #TempMonthTrans Where PresentStatus IN (''W'',''PW'',''PHW'') group by EmployeeId) A1 ON A1.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(PresentStatus) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like ''HD'' group by EmployeeId) A3 ON A3.EmployeeId = T.employeeID
    LEFT Join (Select COUNT(PresentStatus) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like ''H'' group by EmployeeId) A5 ON A5.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(PresentStatus) AS TotLateHours,EmployeeId from #TempMonthTrans Where PresentStatus Like ''LH'' group by EmployeeId) A14 ON A14.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 (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') 
	AND (T.Attn_Date >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''') )
	AND (T.Attn_Date <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
	GROUP BY T.EmployeeId, DM.Displaytitle, OM.Id, OM.Title, Emp.Code, Emp.FirstName, Emp.MiddleName, Emp.LastName, T.Attn_Date, A.TotAbsent, A13.TotPresent, A1.TotWeekOff, A3.TotHalfDay, A5.TotHoliday, A14.TotLateHours
	'
	--WHERE 1=1 and (ED.EmployeeGradeId in (' + convert(nvarchar(100),@rGRadeId) + ') OR (' + convert(nvarchar(100),@rGRadeId) + ') = 0) )' 
	
	execute (@strQuery)
	--print(@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 TotHalfDay,
	--'' as TotHoliday,
	--'' AS TotEarly,
	--'' AS TotLateHours,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as TotHoursOverTime,
	--'' as TotMinutesOverTime,
	--'' as TotHoursEarlyBy,
	--'' as TotMinutesEarlyBy,
	--'' as TotHoursLateBy,
	--'' as TotMinutesLateBy,
	--'' as TotHoursDuration,
	--'' as TotMinutesDuration,
	--'' as TotPresent,
	--'' as TotWeekOff,
	--'' as TotHoliday,
	--'' as LeaveCode1,
	--'' as OrgId,
	--'' as OrganizationTitle
END
GO
PRINT N'Altering Procedure [sBiometric].[pRptMonthlySummaryListDateWiseGet]...';


GO
ALTER PROCEDURE [sBiometric].[pRptMonthlySummaryListDateWiseGet]
	@rOrgGroupId int,
	@rOrgId int,
	@rFromDate DateTime,
	@rToDate DateTime, 
	@rStudentId bigint=0,
	 @rClassId int=0,
	@rDivisionId int=0,
	--@rAttendanceTypeId tinyint,
	--@rAttendanceDate date=0,
-- @rRepeatCount tinyint,
	@rOrgGroupBatchId int=0,
	@rTimeSheetStatus nvarchar(10) = '0',
	@rDepartmentId int=0,
	@rStatusId int=0,
	 @rBuilder1 nvarchar(max),
 @rBuilder2 nvarchar(max),
	 @rIsDetail bit=0
	
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
DECLARE @lBatchID int
CREATE TABLE #TempMonthTrans (
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20),
 ShiftName nvarchar(25) 
	
	)
	SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId = 2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E,D05_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	--IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	--BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
		 AND (((Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) 
		OR ((Month(@rToDate) <> 2 or (((YEAR(@rToDate) % 4 = 0 AND YEAR(@rToDate) % 100 <> 0) OR YEAR(@rToDate) % 400 = 0 And Month(@rToDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
		AND ( SourceTypeId =2003)
	--END
	
	--IF Month(@rFromDate) <> 2
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ((Month(@rFromDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) Or (Month(@rToDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2003)
	--END
	
	--IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ((Month(@rFromDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) OR (Month(@rToDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2003)
	--END
	CREATE TABLE #TempMonthTransWitIoOutTime (EmployeeId bigint,Attn_Date DateTime,InTime nvarchar(20),OutTime nvarchar(20))
	if(@rIsDetail=1)
	BEGIN
	INSERT INTO #TempMonthTransWitIoOutTime
		SELECT  SourceId,Attn_Dt,CONVERT(VARCHAR(10), I.In_Out_Time, 108),CONVERT(VARCHAR(10), O.In_Out_Time, 108)
        FROM [sBiometric].[tCloudTransactionData] I
		OUTER APPLY (
						SELECT TOP 1    In_Out_Time,
										Mode
						FROM [sBiometric].[tCloudTransactionData] t
						WHERE       t.SourceId = I.SourceId
								AND t.In_Out_Time > I.In_Out_Time
								AND SourceTypeid=2003
								AND t.Attn_Dt =I.Attn_Dt
								AND Mode = 'OUT'
						ORDER BY t.In_Out_Time
					) O
		WHERE I.Mode = 'IN'
		AND SourceTypeid=2003
		AND I.Attn_Dt>=@rFromDate
		AND I.Attn_Dt<=@rToDate
		--select * from #TempMonthTransWitIoOutTime
	END

	Select 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2 ,
		SA.AcademicId AS AcademicId,
		SA.StudentId AS StudentId,
		SA.Code AS StudentCode,
		SA.Name AS StudentName,
		ISNULL(SA.RollNo,0) as RollNo,
		ISNULL(TM.FirstIn,'00:00') AS FirstIn,
		ISNULL(TM.LastOut,'00:00') AS LastOut,
		ISNULL(TM.LateBy,'00:00') AS LateBy,
		ISNULL(TM.EarlyBy,'00:00') AS EarlyBy,
		 ISNULL(TM.Duration,'00:00') AS Duration,
		 ISNULL(TM.PresentStatus,'XX') AS OldPresentStatus ,
		  CASE When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
		 When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='PW')AND ([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
		 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW' 
		 ELSE
		TM.PresentStatus END as PresentStatus,
		TM.Attn_Date,
		OM.DisplayTitle AS Organization,
		CM.DisplayTitle AS ClassName,
		CM.Id AS ClassId,
		DM.DisplayTitle AS DivisionName,
		DM.Id AS DivisionId,
		Dept.DisplayTitle AS Department,
		Dept.Id AS DepartmentId,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		Dept.OrderIndex AS OrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.OrgId AS OrgId,
		TM.ShiftName,
		CTD.*,
		@rIsDetail AS IsDetail
				
		From #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND SourceTypeId = 2003  
	 INNER JOIN sStudent.vStudentAcademic SA  ON SA.StudentId = TM.EmployeeId AND MT.SourceTypeId=2003 --AND MT.ATTN_DT = cast(rtrim(YEAR(@rAttendanceDate) *10000+ Month(@rAttendanceDate)  *100+ 01) as datetime)
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
	INNER JOIN sSetup.tDivisionMaster DM  ON  SA.DivisionId=DM.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
	Left Join #TempMonthTransWitIoOutTime CTD ON  CTD.EmployeeId=TM.EmployeeId AND CTD.Attn_Date=TM.Attn_Date  
	INNER JOIN sSetup.tBatchMaster BM ON BC.BatchId = BM.Id AND BM.OrgGroupBatchId=@rOrgGroupBatchId --AND BM.IsActive=1
	WHERE 
		((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND OM.OrgGroupId=@rOrgGroupId
			AND (SA.OrgId=@rOrgId OR @rOrgId=0)
			AND (SA.StudentId=@rStudentId OR @rStudentId=0)
			--AND (SA.BatchId = @rBatchId)
			AND ( (SA.StatusId =  @rStatusId) OR @rStatusId=0)
			AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rToDate)
			 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			 AND (( @rTimeSheetStatus = '1' AND (TM.Duration < '09:30')) OR ( @rTimeSheetStatus != '1' AND ((PresentStatus = @rTimeSheetStatus OR @rTimeSheetStatus='0'))))
			AND (SA.OrgId = @rOrgId OR @rOrgId = 0)
			 AND((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			 AND(( SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			 AND (TM.Attn_Date>=@rFromDate )
			 AND (TM.Attn_Date<=@rToDate)
	ORDER BY SA.RollNo

	DROP Table #TempMonthTrans	

	--Select 
	--	@rBuilder1 AS Builder1,
	--	@rBuilder2 AS Builder2 ,
	--	@rIsDetail AS IsDetail,
	--	CAST(0 AS bigint) AS AcademicId,
	--	'' AS StudentCode,
	--	'' AS StudentName,
	--	0 as RollNo,
	--	'' AS FirstIn,
	--	'' AS LastOut,
	--	'' AS LateBy,
	--	'' AS EarlyBy,
	--	 '' AS Duration,
	--	'' AS OldPresentStatus ,
	--	'' AS PresentStatus,
	--	CAST('' AS Date) AS Attn_Date, 
	--	'' AS Organization,
	--	'' AS ClassName,
	--	0 AS ClassId,
	--	'' AS DivisionName,
	--	0 AS DivisionId,
	--	'' AS Department,
	--	0 AS DepartmentId,
	--	'' As ClassDivision,
	--	0 AS OrderIndex,
	--	0 AS DivisionOrderIndex,
	--	0 AS OrgId,
	--	'' AS ShiftName,
	--	'' AS OutTime,
	--	'' as InTime

END
GO
PRINT N'Altering Procedure [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,
	@OrgGroupDepartmentId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
 
 CREATE TABLE #TempMonthTrans  
 (  
 Id int Identity,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 LateBy nvarchar(20),   
 EarlyBy nvarchar(20), 
 )  
  INSERT INTO #TempMonthTrans  
   
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='W') AND D01_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='W') AND D01_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='H') AND D01_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='H') AND D01_IN = '00:00' THEN 'H'   
			 WHEN (D01 = 'W' OR D01 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN != '00:00' THEN 'P'
			 WHEN D01 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN = '00:00' THEN 'A' 
			 WHEN (D01 = 'H' OR D01 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN != '00:00' THEN 'P'
			 WHEN D01 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN = '00:00' THEN 'A' 
			 --WHEN  AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN != '00:00' THEN 'P'  
			 --WHEN D01 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN != '00:00' THEN 'P'
			 When ((D01='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D01_IN ='00:00'))  then 'A'
			 ELSE D01 END ,	
	D01_L,D01_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	
	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='W') AND D02_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='W') AND D02_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='H') AND D02_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='H') AND D02_IN = '00:00' THEN 'H'   
			 WHEN (D02 = 'W' OR D02 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN != '00:00' THEN 'P'
			 WHEN D02 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN = '00:00' THEN 'A' 
			 WHEN (D02 = 'H' OR D02 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN != '00:00' THEN 'P'
			 WHEN D02 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN = '00:00' THEN 'A' 
			 --WHEN D02 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN != '00:00' THEN 'P'  
			 --WHEN D02 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN != '00:00' THEN 'P'
			  When ((D02='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D02_IN ='00:00'))  then 'A'
			 ELSE D02 END ,	
	D02_L,D02_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='W') AND D03_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='W') AND D03_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='H') AND D03_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='H') AND D03_IN = '00:00' THEN 'H'   
			 WHEN (D03 = 'W' OR D03 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN != '00:00' THEN 'P'
			 WHEN D03 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN = '00:00' THEN 'A' 
			 WHEN (D03 = 'H' OR D03 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN != '00:00' THEN 'P'
			 WHEN D03 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN = '00:00' THEN 'A' 
			 --WHEN D03 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN != '00:00' THEN 'P'  
			 --WHEN D03 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN != '00:00' THEN 'P'
			 When ((D03='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D03_IN ='00:00'))  then 'A'
			 ELSE D03 END ,	
	D03_L,D03_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='W') AND D04_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='W') AND D04_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='H') AND D04_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='H') AND D04_IN = '00:00' THEN 'H'   
			 WHEN (D04 = 'W' OR D04 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN != '00:00' THEN 'P'
			 WHEN D04 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN = '00:00' THEN 'A' 
			 WHEN (D04 = 'H' OR D04 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN != '00:00' THEN 'P'
			 WHEN D04 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN = '00:00' THEN 'A' 
			 --WHEN D04 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN != '00:00' THEN 'P'  
			 --WHEN D04 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN != '00:00' THEN 'P'
			 When ((D04='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D04_IN ='00:00'))  then 'A'
			 ELSE D04 END ,	
	D04_L,D04_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='W') AND D05_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='W') AND D05_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='H') AND D05_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='H') AND D05_IN = '00:00' THEN 'H'   
			 WHEN (D05 = 'W' OR D05 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN != '00:00' THEN 'P'
			 WHEN D05 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN = '00:00' THEN 'A' 
			 WHEN (D05 = 'H' OR D05 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN != '00:00' THEN 'P'
			 WHEN D05 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN = '00:00' THEN 'A' 
			 --WHEN D05 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN != '00:00' THEN 'P'  
			 --WHEN D05 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN != '00:00' THEN 'P'
			  When ((D05='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D05_IN ='00:00'))  then 'A'
			 ELSE D05 END ,	
	D05_L,D05_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='W') AND D06_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='W') AND D06_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='H') AND D06_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='H') AND D06_IN = '00:00' THEN 'H'   
			 WHEN (D06 = 'W' OR D06 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN != '00:00' THEN 'P'
			 WHEN D06 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN = '00:00' THEN 'A' 
			 WHEN (D06 = 'H' OR D06 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN != '00:00' THEN 'P'
			 WHEN D06 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN = '00:00' THEN 'A' 
			 --WHEN D06 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN != '00:00' THEN 'P'  
			 --WHEN D06 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN != '00:00' THEN 'P'
			  When ((D06='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D04_IN ='00:00'))  then 'A'
			 ELSE D06 END ,	
	D06_L,D06_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='W') AND D07_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='W') AND D07_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='H') AND D07_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='H') AND D07_IN = '00:00' THEN 'H'   
			 WHEN (D07 = 'W' OR D07 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN != '00:00' THEN 'P'
			 WHEN D07 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN = '00:00' THEN 'A' 
			 WHEN (D07 = 'H' OR D07 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN != '00:00' THEN 'P'
			 WHEN D07 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN = '00:00' THEN 'A' 
			 --WHEN D07 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN != '00:00' THEN 'P'  
			 --WHEN D07 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN != '00:00' THEN 'P'
			  When ((D07='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D07_IN ='00:00'))  then 'A'
			 ELSE D07 END ,	
	D07_L,D07_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='W') AND D08_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='W') AND D08_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='H') AND D08_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='H') AND D08_IN = '00:00' THEN 'H'   
			 WHEN (D08 = 'W' OR D08 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN != '00:00' THEN 'P'
			 WHEN D08 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN = '00:00' THEN 'A' 
			 WHEN (D08 = 'H' OR D08 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN != '00:00' THEN 'P'
			 WHEN D08 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN = '00:00' THEN 'A' 
			 --WHEN D08 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN != '00:00' THEN 'P'  
			 --WHEN D08 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN != '00:00' THEN 'P'
			  When ((D08='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D08_IN ='00:00'))  then 'A'
			 ELSE D08 END ,	
	D08_L,D08_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='W') AND D09_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='W') AND D09_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='H') AND D09_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='H') AND D09_IN = '00:00' THEN 'H'   
			 WHEN (D09 = 'W' OR D09 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN != '00:00' THEN 'P'
			 WHEN D09 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN = '00:00' THEN 'A' 
			 WHEN (D09 = 'H' OR D09 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN != '00:00' THEN 'P'
			 WHEN D09 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN = '00:00' THEN 'A' 
			 --WHEN D09 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN != '00:00' THEN 'P'  
			 --WHEN D09 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN != '00:00' THEN 'P'
			  When ((D09='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D09_IN ='00:00'))  then 'A'
			 ELSE D09 END ,	
	D09_L,D09_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='W') AND D10_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='W') AND D10_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='H') AND D10_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='H') AND D10_IN = '00:00' THEN 'H'   
			 WHEN (D10 = 'W' OR D10 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN != '00:00' THEN 'P'
			 WHEN D10 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN = '00:00' THEN 'A' 
			 WHEN (D10 = 'H' OR D10 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN != '00:00' THEN 'P'
			 WHEN D10 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN = '00:00' THEN 'A' 
			 --WHEN D10 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN != '00:00' THEN 'P'  
			 --WHEN D10 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN != '00:00' THEN 'P'
			  When ((D10='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D10_IN ='00:00'))  then 'A'
			 ELSE D10 END ,	
	D10_L,D10_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1	

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='W') AND D11_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='W') AND D11_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='H') AND D11_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='H') AND D11_IN = '00:00' THEN 'H'   
			 WHEN (D11 = 'W' OR D11 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN != '00:00' THEN 'P'
			 WHEN D11 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN = '00:00' THEN 'A' 
			 WHEN (D11 = 'H' OR D11 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN != '00:00' THEN 'P'
			 WHEN D11 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN = '00:00' THEN 'A' 
			 --WHEN D11 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN != '00:00' THEN 'P'  
			 --WHEN D11 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN != '00:00' THEN 'P'
			  When ((D11='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D11_IN ='00:00'))  then 'A'
			 ELSE D11 END ,
	D11_L,D11_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='W') AND D12_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='W') AND D12_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='H') AND D12_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='H') AND D12_IN = '00:00' THEN 'H'   
			 WHEN (D12 = 'W' OR D12 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN != '00:00' THEN 'P'
			 WHEN D12 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN = '00:00' THEN 'A' 
			 WHEN (D12 = 'H' OR D12 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN != '00:00' THEN 'P'
			 WHEN D12 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN = '00:00' THEN 'A' 
			 --WHEN D12 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN != '00:00' THEN 'P'  
			 --WHEN D12 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN != '00:00' THEN 'P'
			  When ((D12='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D12_IN ='00:00'))  then 'A'
			 ELSE D12 END ,	
	D12_L,D12_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='W') AND D13_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='W') AND D13_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='H') AND D13_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='H') AND D13_IN = '00:00' THEN 'H'   
			 WHEN (D13 = 'W' OR D13 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN != '00:00' THEN 'P'
			 WHEN D13 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN = '00:00' THEN 'A' 
			 WHEN (D13 = 'H' OR D13 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN != '00:00' THEN 'P'
			 WHEN D13 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN = '00:00' THEN 'A' 
			 --WHEN D13 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN != '00:00' THEN 'P'  
			 --WHEN D13 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN != '00:00' THEN 'P'
			  When ((D13='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D13_IN ='00:00'))  then 'A'
			 ELSE D13 END ,	
	D13_L,D13_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='W') AND D14_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='W') AND D14_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='H') AND D14_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='H') AND D14_IN = '00:00' THEN 'H'   
			 WHEN (D14 = 'W' OR D14 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN != '00:00' THEN 'P'
			 WHEN D14 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN = '00:00' THEN 'A' 
			 WHEN (D14 = 'H' OR D14 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN != '00:00' THEN 'P'
			 WHEN D14 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN = '00:00' THEN 'A' 
			 --WHEN D14 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN != '00:00' THEN 'P'  
			 --WHEN D14 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN != '00:00' THEN 'P'
			  When ((D14='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D14_IN ='00:00'))  then 'A'
			 ELSE D14 END ,	
	D14_L,D14_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='W') AND D15_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='W') AND D15_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='H') AND D15_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='H') AND D15_IN = '00:00' THEN 'H'   
			 WHEN (D15 = 'W' OR D15 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN != '00:00' THEN 'P'
			 WHEN D15 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN = '00:00' THEN 'A' 
			 WHEN (D15 = 'H' OR D15 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN != '00:00' THEN 'P'
			 WHEN D15 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN = '00:00' THEN 'A' 
			 --WHEN D15 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN != '00:00' THEN 'P'  
			 --WHEN D15 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN != '00:00' THEN 'P'
			  When ((D15='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D15_IN ='00:00'))  then 'A'
			 ELSE D15 END ,	
	D15_L,D15_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='W') AND D16_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='W') AND D16_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='H') AND D16_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='H') AND D16_IN = '00:00' THEN 'H'   
			 WHEN (D16 = 'W' OR D16 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN != '00:00' THEN 'P'
			 WHEN D16 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN = '00:00' THEN 'A' 
			 WHEN (D16 = 'H' OR D16 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN != '00:00' THEN 'P'
			 WHEN D16 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN = '00:00' THEN 'A' 
			 --WHEN D16 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN != '00:00' THEN 'P'  
			 --WHEN D16 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN != '00:00' THEN 'P'
			  When ((D16='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D16_IN ='00:00'))  then 'A'
			 ELSE D16 END ,	
	D16_L,D16_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='W') AND D17_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='W') AND D17_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='H') AND D17_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='H') AND D17_IN = '00:00' THEN 'H'   
			 WHEN (D17 = 'W' OR D17 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN != '00:00' THEN 'P'
			 WHEN D17 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN = '00:00' THEN 'A' 
			 WHEN (D17 = 'H' OR D17 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN != '00:00' THEN 'P'
			 WHEN D17 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN = '00:00' THEN 'A' 
			 --WHEN D17 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN != '00:00' THEN 'P'  
			 --WHEN D17 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN != '00:00' THEN 'P'
			  When ((D17='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D17_IN ='00:00'))  then 'A'
			 ELSE D17 END ,	
	D17_L,D17_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='W') AND D18_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='W') AND D18_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='H') AND D18_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='H') AND D18_IN = '00:00' THEN 'H'   
			 WHEN (D18 = 'W' OR D18 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN != '00:00' THEN 'P'
			 WHEN D18 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN = '00:00' THEN 'A' 
			 WHEN (D18 = 'H' OR D18 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN != '00:00' THEN 'P'
			 WHEN D18 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN = '00:00' THEN 'A' 
			 --WHEN D18 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN != '00:00' THEN 'P'  
			 --WHEN D18 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN != '00:00' THEN 'P'
			  When ((D18='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D18_IN ='00:00'))  then 'A'
			 ELSE D18 END ,	
	D18_L,D18_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='W') AND D19_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='W') AND D19_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='H') AND D19_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='H') AND D19_IN = '00:00' THEN 'H'   
			 WHEN (D19 = 'W' OR D19 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN != '00:00' THEN 'P'
			 WHEN D19 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN = '00:00' THEN 'A' 
			 WHEN (D19 = 'H' OR D19 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN != '00:00' THEN 'P'
			 WHEN D19 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN = '00:00' THEN 'A' 
			 --WHEN D19 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN != '00:00' THEN 'P'  
			 --WHEN D19 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN != '00:00' THEN 'P'
			  When ((D19='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D19_IN ='00:00'))  then 'A'
			 ELSE D19 END ,	
	D19_L,D19_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='W') AND D20_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='W') AND D20_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='H') AND D20_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='H') AND D20_IN = '00:00' THEN 'H'   
			 WHEN (D20 = 'W' OR D20 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN != '00:00' THEN 'P'
			 WHEN D20 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN = '00:00' THEN 'A' 
			 WHEN (D20 = 'H' OR D20 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN != '00:00' THEN 'P'
			 WHEN D20 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN = '00:00' THEN 'A' 
			 --WHEN D20 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN != '00:00' THEN 'P'  
			 --WHEN D20 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN != '00:00' THEN 'P'
			  When ((D20='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D20_IN ='00:00'))  then 'A'
			 ELSE D20 END ,		
	D20_L,D20_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='W') AND D21_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='W') AND D21_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='H') AND D21_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='H') AND D21_IN = '00:00' THEN 'H'   
			 WHEN (D21 = 'W' OR D21 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN != '00:00' THEN 'P'
			 WHEN D21 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN = '00:00' THEN 'A' 
			 WHEN (D21 = 'H' OR D21 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN != '00:00' THEN 'P'
			 WHEN D21 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN = '00:00' THEN 'A' 
			 --WHEN D21 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN != '00:00' THEN 'P'  
			 --WHEN D21 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN != '00:00' THEN 'P'
			  When ((D21='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D21_IN ='00:00'))  then 'A'
			 ELSE D21 END ,	
	D21_L,D21_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='W') AND D22_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='W') AND D22_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='H') AND D22_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='H') AND D22_IN = '00:00' THEN 'H'   
			 WHEN (D22 = 'W' OR D22 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN != '00:00' THEN 'P'
			 WHEN D22 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN = '00:00' THEN 'A' 
			 WHEN (D22 = 'H' OR D22 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN != '00:00' THEN 'P'
			 WHEN D22 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN = '00:00' THEN 'A' 
			 --WHEN D22 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN != '00:00' THEN 'P'  
			 --WHEN D22 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN != '00:00' THEN 'P'
			  When ((D22='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D22_IN ='00:00'))  then 'A'
			 ELSE D22 END ,		
	D22_L,D22_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='W') AND D23_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='W') AND D23_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='H') AND D23_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='H') AND D23_IN = '00:00' THEN 'H'   
			 WHEN (D23 = 'W' OR D23 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN != '00:00' THEN 'P'
			 WHEN D23 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN = '00:00' THEN 'A' 
			 WHEN (D23 = 'H' OR D23 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN != '00:00' THEN 'P'
			 WHEN D23 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN = '00:00' THEN 'A' 
			 --WHEN D23 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN != '00:00' THEN 'P'  
			 --WHEN D23 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN != '00:00' THEN 'P'
			  When ((D23='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D23_IN ='00:00'))  then 'A'
			 ELSE D23 END ,	
	D23_L,D23_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='W') AND D24_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='W') AND D24_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='H') AND D24_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='H') AND D24_IN = '00:00' THEN 'H'   
			 WHEN (D24 = 'W' OR D24 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN != '00:00' THEN 'P'
			 WHEN D24 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN = '00:00' THEN 'A' 
			 WHEN (D24 = 'H' OR D24 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN != '00:00' THEN 'P'
			 WHEN D24 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN = '00:00' THEN 'A' 
			 --WHEN D24 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN != '00:00' THEN 'P'  
			 --WHEN D24 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN != '00:00' THEN 'P'
			  When ((D24='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D24_IN ='00:00'))  then 'A'
			 ELSE D24 END ,	
	D24_L,D24_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='W') AND D25_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='W') AND D25_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='H') AND D25_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='H') AND D25_IN = '00:00' THEN 'H'   
			 WHEN (D25 = 'W' OR D25 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN != '00:00' THEN 'P'
			 WHEN D25 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN = '00:00' THEN 'A' 
			 WHEN (D25 = 'H' OR D25 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN != '00:00' THEN 'P'
			 WHEN D25 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN = '00:00' THEN 'A' 
			 --WHEN D25 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN != '00:00' THEN 'P'  
			 --WHEN D25 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN != '00:00' THEN 'P'
			  When ((D25='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D25_IN ='00:00'))  then 'A'
			 ELSE D25 END ,	
	D25_L,D25_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='W') AND D26_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='W') AND D26_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='H') AND D26_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='H') AND D26_IN = '00:00' THEN 'H'   
			 WHEN (D26 = 'W' OR D26 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN != '00:00' THEN 'P'
			 WHEN D26 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN = '00:00' THEN 'A' 
			 WHEN (D26 = 'H' OR D26 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN != '00:00' THEN 'P'
			 WHEN D26 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN = '00:00' THEN 'A' 
			 --WHEN D26 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN != '00:00' THEN 'P'  
			 --WHEN D26 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN != '00:00' THEN 'P'
			  When ((D26='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D26_IN ='00:00'))  then 'A'
			 ELSE D26 END ,	
	D26_L,D26_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='W') AND D27_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='W') AND D27_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='H') AND D27_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='H') AND D27_IN = '00:00' THEN 'H'   
			 WHEN (D27 = 'W' OR D27 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN != '00:00' THEN 'P'
			 WHEN D27 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN = '00:00' THEN 'A' 
			 WHEN (D27 = 'H' OR D27 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN != '00:00' THEN 'P'
			 WHEN D27 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN = '00:00' THEN 'A' 
			 --WHEN D27 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN != '00:00' THEN 'P'  
			 --WHEN D27 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN != '00:00' THEN 'P'
			  When ((D27='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D27_IN ='00:00'))  then 'A'
			 ELSE D27 END ,	
	D27_L,D27_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='W') AND D28_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='W') AND D28_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='H') AND D28_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='H') AND D28_IN = '00:00' THEN 'H'   
			 WHEN (D28 = 'W' OR D28 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN != '00:00' THEN 'P'
			 WHEN D28 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN = '00:00' THEN 'A' 
			 WHEN (D28 = 'H' OR D28 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN != '00:00' THEN 'P'
			 WHEN D28 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN = '00:00' THEN 'A' 
			 --WHEN D28 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN != '00:00' THEN 'P'  
			 --WHEN D28 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN != '00:00' THEN 'P'
			  When ((D28='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D28_IN ='00:00'))  then 'A'
			ELSE D28 END ,	D28_L,D28_E
			FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
			AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1


	IF  @rForMonth <> 2 or ((@rForYear % 4 = 0 AND @rForYear % 100 <> 0) OR @rForYear % 400 = 0 And @rForMonth  =2)
	BEGIN
		INSERT INTO #TempMonthTrans
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='W') AND D29_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='W') AND D29_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='H') AND D29_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='H') AND D29_IN = '00:00' THEN 'H'   
			 WHEN (D29 = 'W' OR D29 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN != '00:00' THEN 'P'
			 WHEN D29 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN = '00:00' THEN 'A' 
			 WHEN (D29 = 'H' OR D29 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN != '00:00' THEN 'P'
			 WHEN D29 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN = '00:00' THEN 'A' 
			 --WHEN D29 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN != '00:00' THEN 'P'  
			 --WHEN D29 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN != '00:00' THEN 'P'
			  When ((D29='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D29_IN ='00:00'))  then 'A'
			 ELSE D29 END ,	
	D29_L,D29_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END
	
	IF @rForMonth <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='W') AND D30_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='W') AND D30_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='H') AND D30_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='H') AND D30_IN = '00:00' THEN 'H'   
			 WHEN (D30 = 'W' OR D30 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN != '00:00' THEN 'P'
			 WHEN D30 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN = '00:00' THEN 'A' 
			 WHEN (D30 = 'H' OR D30 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN != '00:00' THEN 'P'
			 WHEN D30 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN = '00:00' THEN 'A' 
			 --WHEN D30 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN != '00:00' THEN 'P'  
			 --WHEN D30 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN != '00:00' THEN 'P'
			  When ((D30='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D30_IN ='00:00'))  then 'A'
			 ELSE D30 END ,	
	D30_L,D30_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END
	
	IF @rForMonth NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='W') AND D31_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='W') AND D31_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='H') AND D31_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='H') AND D31_IN = '00:00' THEN 'H'   
			 WHEN (D31 = 'W' OR D31 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN != '00:00' THEN 'P'
			 WHEN D31 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN = '00:00' THEN 'A' 
			 WHEN (D31 = 'H' OR D31 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN != '00:00' THEN 'P'
			 WHEN D31 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN = '00:00' THEN 'A' 
			 --WHEN D31 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN != '00:00' THEN 'P'  
			 --WHEN D31 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN != '00:00' THEN 'P'
			  When ((D31='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D31_IN ='00:00'))  then 'A'
			 ELSE D31 END ,	
	D31_L,D31_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END


	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,
		MT.Count_Late AS Count_Late,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='A') AS WeekOffsWiseTotalAbsentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='W') AS WeekOffsWiseTotalWeekOffs,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='H') AS WeekOffsWiseTotalHolidays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND (PresentStatus='P' OR PresentStatus='PW')) AS WeekOffsWiseTotalPresentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='HD') AS WeekOffsWiseTotalHalfDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='LH') AS WeekOffsWiseTotalLessHours,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='E') AS WeekOffsWiseTotalErrorCase

	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)
	AND ((EJD.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 

	DROP Table #TempMonthTrans
END
GO
PRINT N'Altering Procedure [sBiometric].[pShiftAllocationCloudAdd]...';


GO

--exec [sBiometric].[pShiftAllocationCloudAdd] @rXmlDoc=''
ALTER PROC [sBiometric].[pShiftAllocationCloudAdd]
	
		@rXmlDoc nvarchar(MAX)
	
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT
			
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	-----------------------
	CREATE TABLE #tTable  
	(
		SourceId bigint not null
		,SourceTypeId smallint null
		,ShiftCode int null
		,ShiftDay tinyint null		
		,FromShiftDate Datetime null
		,ToShiftDate DateTime null
		,ShiftAllocationId int null
	)

	INSERT INTO #tTable
			   (			    
				SourceId
				,SourceTypeId
				,ShiftCode 
				,ShiftDay 		
				,FromShiftDate 
				,ToShiftDate  
				,ShiftAllocationId 
			   )
	SELECT		
		
		A.SourceId,
		A.SourceTypeId,
		ShiftCode,
		ShiftDay,
		FromShiftDate,
		ToShiftDate,
		ShiftAllocationId
		
	FROM OPENXML (@intDoc, '/Table/ShiftAllocationCloud', 1)
	WITH
	(	
		SourceId bigint '@SourceId'
		,SourceTypeId smallint '@SourceTypeId'
		,ShiftCode int '@ShiftCode'
		,ShiftDay tinyint '@ShiftDay'	
		,FromShiftDate Datetime '@FromShiftDate'
		,ToShiftDate DateTime '@ToShiftDate'
		,ShiftAllocationId int	'@ShiftAllocationId'
	)A 
	select  @intDoc
	INSERT INTO sBiometric.tShiftAllocationCloud
	(
		SourceId,
		SourceTypeId,
		ShiftCode,
		ShiftDay,
		FromShiftDate,
		ToShiftDate
	)
	SELECT
		A.SourceId,
		A.SourceTypeId,
		A.ShiftCode,
		A.ShiftDay,
		A.FromShiftDate,
		A.ToShiftDate				
	FROM #tTable A 
	 WHERE A.SourceId Not in (SELECT SourceId From sBiometric.tShiftAllocationCloud  Where SourceId=A.SourceId  AND SourceTypeId=A.SourceTypeId AND (ShiftDay=A.ShiftDay AND FromShiftDate = A.FromShiftDate))
	 And A.ShiftAllocationId=0
	 --And A.SourceTypeId Not in (SELECT SourceTypeId From sBiometric.tShiftAllocationCloud Where SAC.ShiftDay=A.ShiftDay AND SAC.SourceId=A.SourceId AND SAC.FromShiftDate = A.FromShiftDate)
	
	
	--SELECT * From #tTable
	UPDATE SAC SET SAC.ShiftCode = A.ShiftCode,
				   SAC.ShiftDay=A.ShiftDay,
					SAC.FromShiftDate=A.FromShiftDate,
					SAC.ToShiftDate=A.ToShiftDate
	FROM 
	#tTable A 
	INNER JOIN sBiometric.tShiftAllocationCloud SAC ON SAC.SourceId = A.SourceId AND SAC.SourceTypeId = A.SourceTypeId and SAC.Id=A.ShiftAllocationId
	--WHERE A.Id  in (SELECT SourceId From sBiometric.tShiftAllocationCloud Where ShiftDay=A.ShiftDay AND SourceId=A.SourceId AND FromShiftDate = A.FromShiftDate)
	


	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
END TRY
	BEGIN CATCH
		SELECT -1
	END CATCH

END
GO
PRINT N'Altering Procedure [sBiometric].[pShiftAllocationCloudGet]...';


GO
 
ALTER PROCEDURE [sBiometric].[pShiftAllocationCloudGet]

@rOrgId int = 0,
@rSourceTypeId smallint = 0,
@rSerchBy int=1 --1 for ByDay, 2 For ByDate
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF (@rSourceTypeId=95)
	BEGIN
		SELECT 

			EM.Id AS EmployeeId,
			0 as StudentId,
			'' as StudentCode,
			'' as StudentName,
			EM.Code AS EmployeeCode,
			EM.FirstName + ' ' + EM.LastName AS EmployeeName,
			ISNULL(EM.ShiftId,0) AS CurrentShiftId,
			ISNULL(SA.ShiftCode,0) AS NewShiftId,
			ISNULL(SA.FromShiftDate,'') AS FromShiftDate,
			ISNULL(SA.ToShiftDate,'') AS ToShiftDate,
			ISNULL(SA.ShiftDay,0) AS ShiftDay,
			ISNULL(SA.Id,0) as ShiftAllocationId
		FROM 
			sHrm.tEmployeeMaster EM
			LEFT JOIN sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode = EM.ShiftId
			Inner JOIN sBiometric.tShiftAllocationCloud SA ON SA.SourceId = EM.Id AND SA.SourceTypeId=95 
				AND ((@rSerchBy=1 And SA.ShiftDay<>0 ) or (@rSerchBy=2 And SA.ShiftDay=0))
		WHERE
			EM.OrgID = @rOrgId AND EM.StatusId=7
		Union All
			SELECT 

			EM.Id AS EmployeeId,
			0 as StudentId,
			'' as StudentCode,
			'' as StudentName,
			EM.Code AS EmployeeCode,
			EM.FirstName + ' ' + EM.LastName AS EmployeeName,
			ISNULL(EM.ShiftId,0) AS CurrentShiftId,
			0 AS NewShiftId,
			'' AS FromShiftDate,
			'' AS ToShiftDate,
			0 AS ShiftDay,
			0 as ShiftAllocationId
		FROM 
			sHrm.tEmployeeMaster EM
			LEFT JOIN sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode = EM.ShiftId
			
		WHERE
			EM.OrgID = @rOrgId AND EM.StatusId=7

		Order by EmployeeId,ShiftAllocationId
			
	END
ELSE IF(@rSourceTypeId=2003)
	BEGIN
			SELECT 
				SM.Id AS StudentId,
				SM.Code AS StudentCode,
				SM.FirstName + ' ' + SM.LastName AS StudentName,
				ISNULL(SM.ShiftId,0) AS CurrentShiftId,
				ISNULL(SA.ShiftCode,0) AS NewShiftId,
				ISNULL(SA.FromShiftDate,'') AS FromShiftDate,
				ISNULL(SA.ToShiftDate,'') AS ToShiftDate,
				ISNULL(SA.ShiftDay,0) AS ShiftDay,
				0 as EmployeeId,
				'' as EmployeeCode,
				'' as EmployeeName,
				ISNULL(SA.Id,0) as ShiftAllocationId
			FROM 
				sStudent.tStudentMaster SM
				LEFT JOIN sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode = SM.ShiftId
				Inner JOIN sBiometric.tShiftAllocationCloud SA ON SA.SourceId = SM.Id	AND SA.SourceTypeId=2003
					AND ((@rSerchBy=1 And SA.ShiftDay<>0 ) or (@rSerchBy=2 And SA.ShiftDay=0))
			WHERE
				SM.OrgID = @rOrgId AND SM.StatusId=1
		Union All
			SELECT 
				SM.Id AS StudentId,
				SM.Code AS StudentCode,
				SM.FirstName + ' ' + SM.LastName AS StudentName,
				ISNULL(SM.ShiftId,0) AS CurrentShiftId,
				0 AS NewShiftId,
				'' AS FromShiftDate,
				'' AS ToShiftDate,
				0 AS ShiftDay,
				0 as EmployeeId,
				'' as EmployeeCode,
				'' as EmployeeName,
				0 as ShiftAllocationId
			FROM 
				sStudent.tStudentMaster SM
				LEFT JOIN sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode = SM.ShiftId
				
			WHERE
				SM.OrgID = @rOrgId AND SM.StatusId=1	
			Order by StudentId,ShiftAllocationId
	END
END
GO
PRINT N'Altering Procedure [sBiometric].[pShiftMasterCloudAdd]...';


GO

 
ALTER PROCEDURE [sBiometric].[pShiftMasterCloudAdd]
@rShiftCode int = 0,
@rShiftName nvarchar(50),
@rStartTime DateTime = null,
@rEndTime DateTime = null,
@rGraceBefore int = 0,
@rGraceAfter int = 0,
@rShiftDur nvarchar(16) = NULL,
@rMinHrsHalfDay  nvarchar(16) = null,
@rMinHrsFullDay nvarchar(16) = null,
@rAlterGraceTime int = 0,
@IsOutTimeAlertTime bit = 0,
@OutTimeAlertTime DateTime = null,
@rOrgGroupId int = 0,
@rLastOutAlertBasedOnId int=1,
@rIsStopInTimeAlertTime bit=0,
@rStopInTimeAlertTime DateTime=null

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	IF(@rShiftcode = 0)	
		BEGIN
			If Exists(select ShiftCode from sBiometric.tShiftMasterCloud where ShiftName=@rShiftName and OrgGroupId = @rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
			END 
		END
	ELSE
		BEGIN
			If  Exists(select ShiftCode from sBiometric.tShiftMasterCloud where ShiftName=@rShiftName AND Shiftcode<>@rShiftcode and OrgGroupId = @rOrgGroupId)
			Begin
				select -103 as Result
				RETURN
			End
		END	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 IF EXISTS (SELECT 1 FROM sBiometric.tShiftMasterCloud)
	 BEGIN
		SELECT @lNextNumber = Max(ISNULL(ShiftCode,0)) + 1 FROM sBiometric.tShiftMasterCloud
	 END
	 ELSE
	 BEGIN
		SET @lNextNumber = 1
	 END
	 
	IF(@rShiftcode = 0)	
	BEGIN
	Insert into sBiometric.tShiftMasterCloud 
     (ShiftCode
     , ShiftName
     , StartTime
     , EndTime
     , GraceBefore
     , GraceAfter
     , ShiftDur
     , MinHrsHalfDay
     , MinHrsFullDay    
     , AlterGraceTime
     , IsOutTimeAlertTime
     , OutTimeAlertTime
     , OrgGroupId
	 ,LastOutAlertBasedOnId
	 ,IsStopInTimeAlertTime
	 ,StopInTimeAlertTime)
     Values
     (@lNextNumber
     ,@rShiftName
     ,@rStartTime
     ,@rEndTime
     ,@rGraceBefore
     ,@rGraceAfter
     ,@rShiftDur
     ,@rMinHrsHalfDay
     ,@rMinHrsFullDay
     ,@rAlterGraceTime
     ,@IsOutTimeAlertTime
     ,@OutTimeAlertTime
     ,@rOrgGroupId
     ,@rLastOutAlertBasedOnId
	 ,@rIsStopInTimeAlertTime 
	 ,@rStopInTimeAlertTime 
	 )
     
     SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	    UPDATE sBiometric.tShiftMasterCloud
	    SET
			ShiftName=@rShiftName,
			StartTime=@rStartTime,
			EndTime=@rEndTime,
			GraceBefore=@rGraceBefore,
			shiftDur=@rShiftDur,
			MinHrsHalfDay=@rMinHrsHalfDay,
			MinHrsFullDay=@rMinHrsFullDay,
			AlterGraceTime=@rAlterGraceTime,
		    IsOutTimeAlertTime = @IsOutTimeAlertTime,
			OutTimeAlertTime = @OutTimeAlertTime,
			LastOutAlertBasedOnId=@rLastOutAlertBasedOnId,
			IsStopInTimeAlertTime=@rIsStopInTimeAlertTime,
			StopInTimeAlertTime=@rStopInTimeAlertTime,
			GraceAfter=@rGraceAfter
		
	      WHERE ShiftCode = @rShiftcode and OrgGroupId = @rOrgGroupId
	      
	      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 Procedure [sBiometric].[pTimeSheetListGet]...';


GO

ALTER PROCEDURE [sBiometric].[pTimeSheetListGet]
  @rEmployeeId bigint=0,  
  @rFromDate DateTime,  
  @rToDate DateTime,  
  @rStatus nvarchar(10) = '0',  
  @rOrgId int = 0  ,
  @rEmployeeName nvarchar(50) = '',
  @rStatusId int = 0,
  @rOrganizationDepartmentId int=0,
  @rOrgGroupDepartmentId int = 0
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
  
 CREATE TABLE #TempMonthTrans  
 (  
 Id int Identity,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20),
 ShiftName nvarchar(25)  
 )  
    Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		DECLARE @lBatchID int
		DECLARE @lForYear nvarchar(20),@lForMonth nvarchar(20)
		Set @lForYear = Year(@rFromDate)
		
		Set @lForMonth = Month(@rFromDate)
		
		Set @ldate= CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@lForMonth,@lForYear)
		
		set @Firstdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @Lastdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), @Days)

		SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
   
 INSERT INTO #TempMonthTrans  
   
 	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E,D05_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	


 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),1,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),1,0,0,@rOrgId) else D01 end as D01,  
 --D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),2,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),2,0,0,@rOrgId) else D02 end as D02,  
 --D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),3,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),3,0,0,@rOrgId) else D03 end as D03,  
 --D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),4,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),4,0,0,@rOrgId) else D04 end as D04,  
 --D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),5,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),5,0,0,@rOrgId) else D05 end as D05,  
 --D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),6,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),6,0,0,@rOrgId) else D06 end as D06,  
 --D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),7,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),7,0,0,@rOrgId) else D07 end as D07,  
 --D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),8,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),8,0,0,@rOrgId) else D08 end as D08,  
 --D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime), case When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),9,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),9,0,0,@rOrgId) else D09 end as D09,  
 --D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),10,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),10,0,0,@rOrgId) else D10 end as D10,  
 --D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),11,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),11,0,0,@rOrgId) else D11 end as D11,  
 --D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),12,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),12,0,0,@rOrgId) else D12 end as D12,  
 --D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),13,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),13,0,0,@rOrgId) else D13 end as D13,  
 --D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),14,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),14,0,0,@rOrgId) else D14 end as D14,  
 --D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),15,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),15,0,0,@rOrgId) else D15 end as D15,  
 --D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),16,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),16,0,0,@rOrgId) else D16 end as D16,  
 --D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),17,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),17,0,0,@rOrgId) else D17 end as D17,  
 --D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),18,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),18,0,0,@rOrgId) else D18 end as D18,  
 --D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),19,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),19,0,0,@rOrgId) else D19 end as D19,  
 --D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),20,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),20,0,0,@rOrgId) else D20 end as D20,  
 --D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),21,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),21,0,0,@rOrgId) else D21 end as D21,  
 --D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),22,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),22,0,0,@rOrgId) else D22 end as D22,  
 --D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),23,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),23,0,0,@rOrgId) else D23 end as D23,  
 --D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),24,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),24,0,0,@rOrgId) else D24 end as D24,  
 --D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),25,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),25,0,0,@rOrgId) else D25 end as D25,  
 --D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),26,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),26,0,0,@rOrgId) else D26 end as D26,  
 --D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),27,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),27,0,0,@rOrgId) else D27 end as D27,  
 --D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),28,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),28,0,0,@rOrgId) else D28 end as D28,  
 --D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))   
 --BEGIN  
 -- INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),29,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),29,0,0,@rOrgId) else D29 end as D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  
   
 --IF Month(@rFromDate) <> 2  
 --BEGIN  
 --INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),30,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),30,0,0,@rOrgId) else D30 end as D30,  
 --D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  
   
 --IF Month(@rFromDate) NOT IN (2,4,6,9,11)  
 --BEGIN  
 --INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),31,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),31,0,0,@rOrgId) else D31 end as D31,  
 --D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  

 --SELECT * FROM #TempMonthTrans
 --SELECT TM.*,
 
       
		
 SELECT TM.Id,TM.EmployeeId,TM.Attn_Date,TM.PresentStatus AS OldPresentStatus,OGD.Title AS [Organization Group Department],
 
 CASE When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
 When ((TM.PresentStatus='PW')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW'
  When ((TM.PresentStatus='XX')AND (Cast(TM.Attn_Date as date)<GETDATE()) And (cast(EJD.DateOfJoining as date)<= Cast(TM.Attn_Date as date) OR ISNULL(EJD.DateOfJoining,'')='')AND (EJD.DateOfleaving>= Cast(TM.Attn_Date as date) OR ISNULL(EJD.DateOfleaving,'')='') AND (TM.FirstIn ='00:00'))  then 'A'
 ELSE
 TM.PresentStatus END as PresentStatus,
 TM.FirstIn,TM.LastOut,TM.OverTime,TM.LateBy,TM.Duration,TM.EarlyBy,TM.ShiftName, MT.Tot_Attn,
 MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,  
 Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave,EM.FirstName + ' ' + EM.LastName As ShortName,EM.Code as EmpCode ,   
 [sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus ,   
 [sBiometric].[fEmployeeLeaveTypePendingGet](TM.ATTN_DATE,TM.EmployeeId) AS LeavePendingStatus,   
 [sBiometric].[fEmployeeTravelGet](TM.ATTN_DATE,TM.EmployeeId) AS EmployeeTravel,  
 ISNULL(ELS.Id,0) AS EmployeeLateStatusId, 
 ISNULL(SM.Id,0) AS StatusId,  
 ISNULL(SM.Title,'') AS Status  
 FROM #TempMonthTrans TM   
 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
 INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId  
 LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)  
 LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId  
 --INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(EJD.DateOfJoining,'1900/01/01'))
 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(cast(rtrim(YEAR(EJD.DateOfJoining) *10000+ Month(EJD.DateOfJoining) *100+ 01) as datetime),'1900/01/01'))
 INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
 LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id
 WHERE   
 TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate    
 AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
 AND (( @rStatus = '1' AND (TM.Duration < '09:30')) OR ( @rStatus != '1' AND ((PresentStatus = @rStatus OR @rStatus='0'))))
 AND EM.OrgId = @rOrgId 
 AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
 AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
 AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
 AND (EM.FirstName + ' ' + EM.LastName like '%' + @rEmployeeName + '%' or @rEmployeeName = '')
 AND  ISNULL(EM.IsOtherUser,0) = 0
 AND (EJD.DateOfJoining<= @Lastdate OR ISNULL(EJD.DateOfJoining,'')='')
 AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
 --AND (TM.Duration < '09:30')
 Order By TM.EmployeeId,TM.Attn_Date


 


END
GO
PRINT N'Altering Procedure [sCertificate].[pRptTransferCertificateNewGet]...';


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

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

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

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

	--add for 27638 mantis start
	DECLARE @lIsShowPhoto bit = 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
	--add for 27638 mantis end

	SELECT  
		T.Number,
		T.TCDate AS TransferDate,
		T.ExamName,
		T.ExamSeatNo,
		T.ExamYear,
		T.ExamResult,
		T.PromotedClass,
		T.TransferConduct,
		T.OptionalSubject,
		T.Remark,
		A.Name,
		A.OrganiZationName,
	    SO.GenderId,
	    SO.DateOfBirth,
	    A.ClassName AS ClassName,
		A.DivisionName AS DivisionName,
		A.Code As StudentCode,
		SO.AdhaarNumber,
		T.SemesterDuration,
		A.StudentId,
		@lIsOnPrePrinted AS IsOnPrePrinted,
		@lIsDisplayImageHeader AS IsDisplayImageHeader,
		OM.OrgLogo,
		OM.ReportOrgTitle AS OrgTitle,
		OM.SmallAddress1,
		OM.SmallAddress2,
		OM.RegistrationDetail,
		--OI.CertificateHeaderA4,
		@lIDConfigValue AS ItemValue,
		OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
		ISNULL(SF.FatherName,'') As FatherName,			--add for 27638 mantis start
		ISNULL(SF.MotherName,'') As MotherName,
		A.StatusId,
		SI.StudentPhoto,
		@lIsShowPhoto AS IsShowPhoto,
		CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
		ISNULL(SI.QRCode,'') AS QRCode,
		SC.PresentStreetOne,
		SC.PresentStreetTwo,
		SC.PresentStreetThree,
		SC.PresentCountry,
		SC.PresentState,
		SC.PresentCity,
		SC.PresentZipCode,
		SC.PresentContactNo,
		SC.PermanentStreetOne,
		SC.PermanentStreetTwo,
		SC.PermanentStreetThree,
		SC.PermanentCountry,
		SC.PermanentState,
		SC.PermanentCity,
		SC.PermanentZipCode,
		SC.PermanentContactNo		--add for 27638 mantis end
		
	From sCertificate.tTransfer T 
	INNER JOIN sStudent.vStudentAcademic A On A.AcademicId=T.AcademicId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId  
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId 
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId		--add for 27638 mantis
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId			--add for 27638 mantis
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId		--add for 27638 mantis
	WHERE 
		T.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((A.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((T.TCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((T.TCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((A.ClassId=@rClassId) OR(@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((T.Number=@rNumber) OR (@rNumber=''))
		AND ((T.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((T.Number <= @rToNo) OR (@rToNo=''))
	
END
GO
PRINT N'Altering Procedure [sCommunication].[pCircularConsentGet]...';


GO

ALTER PROCEDURE [sCommunication].[pCircularConsentGet]
	 
        @rCircularId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT
		CC.Id AS CircularConsentId,
		ISNULL(CC.QuestionDescription,'')AS QuestionDescription,
		ISNULL(CC.AnsFieldTypeId,0)AS AnsFieldTypeId,
		ISNULL(CC.AnsFieldList,'') AS AnsFieldList
	FROM [sCommunication].[tCircularConsent] CC
	WHERE CircularId = @rCircularId
END
GO
PRINT N'Altering Procedure [sCommunication].[pMyUpdateGet]...';


GO


--------------------
ALTER PROCEDURE [sCommunication].[pMyUpdateGet]  
@rOrgId int,    
@rBatchId int,  
@rOrgGroupBatchId int,  
@rUserId bigint,  
@rUserSourceId bigint,  
@rUserSourceTypeId int,  
@rSyncedAssignmentId bigint,  
@rSyncedCircularId bigint,  
@rSyncedPollId bigint,  
@rSyncedQueryCommentId bigint,  
@rSyncedNewsId bigint,  
@rSyncedBlogId bigint,  
@rSyncedBehaviourId bigint,  
@rSyncedActivityId bigint,  
@rSyncedResultId bigint,  
@rSyncedAssignTaskId bigint,  
@rSyncedPhotoCategoryId int,  
@rVersionNumber nvarchar(Max)='',  
@rDeviceToken nvarchar(200)='',  
@rOSTypeId smallint = 0,
@rAppVersion nvarchar(20)='',
@rAppName nvarchar(100)=''

 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
 DECLARE @lAcademicId bigint,  
  @lScopeSourceId int,  
  @lScopeSourceTypeId int,  
  @lStudentId bigint,  
  @lClassId int,  
  @lDivisionId int,  
  @lOrgId int,  
  @lDepartmentId int,  
  @lAssignmentStatus bit=0,  
  @lCircularStatus bit=0,  
  @lPollStatus bit=0,  
  @lQueryStatus bit=0,  
  @lBlogStatus bit=0,  
  @lNewsStatus bit=0,  
  @lBehaviourStatus bit=0,  
  @lActivityStatus bit=0,  
  @lResultStatus bit=0,  
  @lAssignTaskStatus bit=0,  
  @lPhotoCategoryStatus bit=0,  
  @lIsActive bit=0,  
  @lIsOptimizeAppImageUpload bit=0  
  
IF( @rUserSourceTypeId = 2003)   
BEGIN  
  SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId  
  FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM  
 ON A.BatchId = BM.Id AND BM.IsActive = 1   
 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId  
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
--SELECT @lAcademicId = Id, @lScopeSourceId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rUserSourceId AND BatchId = @rBatchId  
SET @lScopeSourceId = @lDivisionId  
SET @lScopeSourceTypeId = 2005  
END  
ELSE  
BEGIN  
 SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId  FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD  
    ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId AND ISNULL(EM.IsOtherUser,0) = 0  
--SELECT @lScopeSourceId = OrganizationDepartmentId FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId  
SET @lScopeSourceId = @lDepartmentId  
SET @lScopeSourceTypeId = 2004  
END  
--IF EXISTS(SELECT 1 FROM sCommunication.tAssignmentScope ASO INNER JOIN  sCommunication.tAssignment A  
-- ON A.Id = ASO.AssignmentId  
--WHERE ASO.AssignmentId > @rSyncedAssignmentId AND ASO.SourceTypeId = @lScopeSourceTypeId AND ASO.SourceId = @lScopeSourceId AND A.BatchId=@rBatchId)  
--SET @lAssignmentStatus = 1  
  
  
--IF( @rUserSourceTypeId = 2003)   
--BEGIN  
  
--    IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS WHERE  
--      ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId)   
--      OR (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId)  
--      OR (CS.SourceTypeId = 2016 AND CS.SourceId =@lClassId)  
--      OR (CS.SourceTypeId = 2005 AND CS.SourceId =@lDivisionId)  
--      OR (CS.SourceTypeId = 2003 AND CS.SourceId =@lStudentId)  
--      OR (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId)  
--      )  
--       AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D ON D.CircularId= C.Id  
--      --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId  
--        WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)  
--        AND C.AssigneeId IN (1,2) AND C.OrgGroupBatchId=@rOrgGroupBatchId)   
--      SET @lCircularStatus = 1  
  
--END   
--ELSE  
--BEGIN  
-- IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS  
--       WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId))  
--       AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D ON D.CircularId= C.Id  
--       --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId  
--       WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)  
--       AND C.AssigneeId IN (1,3) AND C.OrgGroupBatchId=@rOrgGroupBatchId)   
--     SET @lCircularStatus = 1         
  
--END  
--IF EXISTS(SELECT 1 FROM sCommunication.tCircularScope WHERE  CircularId > @rSyncedCircularId AND SourceTypeId = @lScopeSourceTypeId AND SourceId = @lScopeSourceId)  
--SET @lCircularStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tPoll P INNER JOIN sCommunication.tPollMember PM ON P.Id=PM.PollId  
-- WHERE PM.PollId > @rSyncedPollId AND PM.SourceTypeId = @lScopeSourceTypeId AND PM.SourceId = @lScopeSourceId AND P.OrgGroupBatchId=@rOrgGroupBatchId)  
--SET @lPollStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tBlogScope BS INNER JOIN sCommunication.tBlog B  
--ON B.Id = BS.BlogId  
--WHERE B.IsPublish = 1 AND BS.BlogId > @rSyncedBlogId AND BS.SourceTypeId = 2021 AND BS.SourceId = @rOrgId AND B.OrgGroupBatchId = @rOrgGroupBatchId)  
--SET @lBlogStatus = 1  
  
--IF EXISTS(SELECT 1 FROM  sCommunication.tNews N INNER JOIN sCommunication.tNewsScope NS ON N.Id=NS.NewsId   
--   WHERE NS.NewsId > @rSyncedNewsId AND NS.SourceTypeId = 2021 AND NS.SourceId = @rOrgId AND N.OrgGroupBatchId = @rOrgGroupBatchId)  
--SET @lNewsStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tNewsScope WHERE NewsId > @rSyncedNewsId AND SourceTypeId = @rOrgId AND SourceId = 1016)  
--SET @lNewsStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tUploadResult WHERE Id > @rSyncedResultId AND DivisionId = @lScopeSourceId AND BatchId=@rBatchId AND IsObsolete=0 )  
--SET @lResultStatus = 1  
  
--IF EXISTS(SELECT 1 FROM    
--sCommunication.tPhotoCategoryMaster PCM  
--INNER JOIN sCommunication.tPhotoCategoryScope PCO   
--ON PCM.Id=PCO.PhotoCategoryId WHERE PCM.Id > @rSyncedPhotoCategoryId AND LEFT(PCO.ScopeSourceId,4) = @rOrgId  AND PCM.IsObsolete=0 )  
--SET @lPhotoCategoryStatus = 1  
  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tAssignTask WHERE  Id > @rSyncedAssignTaskId AND AssignedToSourceTypeId = @rUserSourceTypeId   
--AND AssignedToSourceId = @rUserSourceId AND IsCompleted=0 AND IsClosed=0 AND OrgId=@rOrgId)  
--SET @lAssignTaskStatus = 1  
  
  
--IF EXISTS(SELECT 1 FROM  sActivity.tActivity A INNER JOIN sActivity.tActivityParticipant AP ON A.Id=AP.ActivityId  
-- WHERE AP.ActivityId > @rSyncedActivityId AND AP.SourceTypeId = @rUserSourceTypeId AND AP.SourceId = @rUserSourceId AND A.BatchId=@rBatchId)  
--SET @lActivityStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tBehaviour WHERE Id > @rSyncedBehaviourId AND AcademicId = @lAcademicId )  
--SET @lBehaviourStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tQuery Q INNER JOIN sCommunication.tQueryComment QC ON Q.Id=QC.QueryId  
--WHERE Q.CreatedUserId=@rUserId AND Q.IsUserView=0 AND QC.Id>@rSyncedQueryCommentId AND QC.CreatedUserId <> @rUserSourceId AND Q.OrgGroupBatchId=@rOrgGroupBatchId)  
--SET @lQueryStatus = 1  
   
IF(@rUserSourceTypeId = 2003)  
BEGIN   
 DECLARE @lStatusId1 smallint=0  
  SELECT @lStatusId1 = StatusId FROM sStudent.tStudentMaster SM WHERE Id = @rUserSourceId  
 IF(@lStatusId1=1)  
 BEGIN   
  SET @lIsActive = 1  
 END ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
ELSE IF(@rUserSourceTypeId = 95)  
BEGIN   
 DECLARE @lStatusId2 smallint=0  
 SELECT @lStatusId2 = StatusId FROM sHrm.tEmployeeMaster EM WHERE Id = @rUserSourceId --AND ISNULL(EM.IsOtherUser,0) = 0  
 IF(@lStatusId2=7)  
 BEGIN   
  SET @lIsActive = 1  
 END ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
ELSE IF(@rUserSourceTypeId = 1)  
BEGIN   
 DECLARE @IsObsolete smallint=0 
 SELECT @IsObsolete=ISNULL(IsObsolete,0) FROM sSecurity.tUser WHERE Id = @rUserId  
 IF(@IsObsolete=0)  
 BEGIN   
  SET @lIsActive = 1  
 END   
 ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
  
IF(@lIsActive=1)  
BEGIN  
 DECLARE @lIsObsolete bit=0  
 SELECT @lIsObsolete=ISNULL(IsObsolete,0) FROM sSecurity.tUser WHERE Id = @rUserId  
  
 IF(@lIsObsolete=0)  
  SET @lIsActive = 1  
 ELSE  
  SET @lIsActive = 0  
END  
  
  
DECLARE @lOrgGroupId int=0  
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id =@rOrgId  
DECLARE @lOptimizeAppImageUpload nvarchar(50)  
SELECT @lOptimizeAppImageUpload = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 247 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
IF (@lOptimizeAppImageUpload IS NULL) OR (@lOptimizeAppImageUpload = 'False')  
 SET @lIsOptimizeAppImageUpload = 0  
ELSE  
 SET @lIsOptimizeAppImageUpload = 1   
   
DECLARE @lAlertRemark nvarchar(2000) = ''  
   
--IF(@rVersionNumber IS NULl OR @rVersionNumber='')  
--BEGIN  
-- DECLARE @lUserName nvarchar(100)=''  
-- DECLARE @lUserPassword nvarchar(100)=''  
-- DECLARE @lBatch nvarchar(100)=''  
-- SELECT @lBatch = Title  FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
   
-- SELECT @lUserName=UserName,@lUserPassword=UserPassword FROM sSecurity.tTempUser WHERE UserId = @rUserId  
-- SET @lAlertRemark = 'Plese install the new app from this location (https://play.google.com/store/apps/details?id=com.vidyalaya.pinnacleschoolgandhinagarnew) Uninstall the old app. Login in new app with  
--       Registration Number : '+LEFT(@rOrgGroupBatchId,4) +'  
--       User Name : '+@lUserName+'  
--       Password : '+@lUserPassword+'  
--       Batch :' + @lBatch  
--END  
--ELSE   
BEGIN  
 SELECT @lAlertRemark=AlertRemark FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @lOrgGroupId  
END  
  
DECLARE @lMobileAppModuleAutoSyncToken nvarchar(50)  
SELECT @lMobileAppModuleAutoSyncToken = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 317 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
  
  
DECLARE @lIsStopApplicationAccess bit=0  
DECLARE @lStudentCustomAlert nvarchar(1000)=''  
IF(@rUserSourceTypeId=2003)  
SELECT @lIsStopApplicationAccess = ISNULL(IsStopApplicationAccess,0) ,@lStudentCustomAlert= ISNULL(StudentCustomAlert,'') FROM sStudent.tStudentCommunication WHERE StudentId = @rUserSourceId  
  
  
IF(LEN(@rDeviceToken) > 0)  
BEGIN   
 DECLARE @lDeviceToken nvarchar(200)=''  
 SELECT @lDeviceToken = DeviceToken FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId  
  
 DECLARE @lConfigValue nvarchar(50)=''  
 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 374 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
  
 IF @lConfigValue IS NULL   
 SET @lConfigValue = 'False'  
  
 IF @lConfigValue = 'True'  
 BEGIN  
 IF(@lDeviceToken!=@rDeviceToken)  
  SET @lIsActive=0  
 END  
 
 SET @lDeviceToken = (SELECT DeviceToken FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND DeviceToken=@rDeviceToken)  	
 IF(@lDeviceToken IS NULL OR @lDeviceToken='' OR ISNULL(@lDeviceToken,'') = '')  
  SET @lIsActive=0  
END  
  
DECLARE @lActiceClassBatchId NVARCHAR(MAX) = '',@lBatchClassId int  
   
IF(@rUserSourceTypeId = 2003)  
BEGIN   
 SELECT @lBatchClassId = A.ClassId  
 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 StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
  
 IF EXISTS(SELECT BatchId FROM [sSetup].[tBatchClass] BC INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BC.BatchId WHERE ClassId = @lBatchClassId AND IsBatchClassActive = 1 AND BM.IsActive = 1)  
 BEGIN  
  SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,BC.BatchId)+','+ BM.Title FROM [sSetup].[tBatchClass] BC INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BC.BatchId WHERE BC.ClassId = @lBatchClassId AND BC.IsBatchClassActive = 1 AND BM.IsActive = 1  
 END  
 ELSE  
 BEGIN  
  SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,Id) +','+ Title FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
 END  
END  
ELSE IF(@rUserSourceTypeId = 95)  
BEGIN  
 SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,Id) +','+ Title FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
END  


IF(LEN(ISNULL(@rAppVersion,'')) > 0 AND LEN(ISNULL(@rAppVersion,'')) > 0)
BEGIN
	UPDATE sCommunication.tRegisteredUsers
	SET
		AppVersion = @rAppVersion,
		AppName = @rAppName,
		UpdatedDateTime = sCommon.fGetDate(),
		DeviceDetail = @rVersionNumber
	WHERE 
		DeviceToken = @rDeviceToken 
		AND OsTypeId = @rOSTypeId
		AND OrgId=@rOrgId AND UserId=@rUserId 
		AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId
END
CREATE TABLE #Module (  
Id int,  
Title nvarchar(2000),  
IsNew bit )  
INSERT INTO #Module VALUES (1,'IsActiveCheck',CONVERT(bit,@lIsActive))  
INSERT INTO #Module VALUES (2,'IsOptimizeAppImageUpload',@lIsOptimizeAppImageUpload)  
INSERT INTO #Module VALUES (3,ISNULL(@lAlertRemark,''),1)  
INSERT INTO #Module VALUES (4,ISNULL(@lMobileAppModuleAutoSyncToken,0),1)  
INSERT INTO #Module VALUES (5,'Is Stop Application Access',@lIsStopApplicationAccess)  
INSERT INTO #Module VALUES (6,@lStudentCustomAlert,1)  
INSERT INTO #Module VALUES (20085,'Circular',0)  
INSERT INTO #Module VALUES (20088,'Query',0)  
INSERT INTO #Module VALUES (20099,'Blog',0)  
INSERT INTO #Module VALUES (20104,'News',0)  
INSERT INTO #Module VALUES (20172,'AssignTask',0)  
INSERT INTO #Module VALUES (20183,'Gallery',0)  
INSERT INTO #Module VALUES (20204,'Poll',0)  
INSERT INTO #Module VALUES (20093,'Assignment',0)  
INSERT INTO #Module VALUES (20209,'Activity',0)  
INSERT INTO #Module VALUES (20130,'Behaviour',0)  
INSERT INTO #Module VALUES (20180,'Result',0)  
INSERT INTO #Module VALUES (7,@lActiceClassBatchId,1)  
   
SELECT * FROM #Module  
   
--SELECT @lAssignmentStatus AS Assignment,@lCircularStatus AS Circular,@lPollStatus AS Poll,@lQueryStatus AS Query,  
--@lBlogStatus AS Blog,@lNewsStatus AS News,@lBehaviourStatus AS Behaviour,  
--@lActivityStatus AS Activity,@lResultStatus AS Result,@lAssignTaskStatus AS AssignTask,@lPhotoCategoryStatus AS Gallery  
  
END
GO
PRINT N'Altering Procedure [sCommunication].[pStudentResultGet]...';


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


GO

ALTER PROCEDURE [sEMeeting].[pMeetingAccountGet]
		@rOrgGroupId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT
		OMA.Id,
		OMA.AccountName AS Title
		FROM sAcademic.tOnlineMeetingAccount OMA
		WHERE ISNULL(OMA.IsObsolete,0) = 0 AND OMA.OrgGroupId =  @rOrgGroupId
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END
GO
PRINT N'Altering Procedure [sEMeeting].[pOnlineMeetingTeacherGet]...';


GO

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingTeacherGet]
	 
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rOrgGroupId int,
	 @rUserId bigint,
	 @rIsOnlineLearningAdmin bit
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	BEGIN TRY
	If (@rSourceTypeId = 95)
		BEGIN
		if(@rIsOnlineLearningAdmin = 1)
			BEGIN
			SELECT EM.EmployeeId as Id, 
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title 
			FROM sHrm.vExtEmployee EM 
			INNER JOIN sSetup.vUserOrganization OM ON OM.Id = EM.OrgId INNER JOIN sSetup.tOrganizationMaster OrgM 
			ON OrgM.Id=EM.OrgId 
			WHERE ISNULL(IsOtherUser,0) = 0 AND  StatusId =7  AND EmployeeGroupId = 1 AND OM.OrgGroupId = @rOrgGroupId AND OM.UserId = @rUserId
			ORDER BY Title
			END
		else
			BEGIN
			SELECT EM.EmployeeId as Id, 
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title 
			FROM sHrm.vExtEmployee EM 
			INNER JOIN sSetup.tOrganizationMaster OrgM 
			ON OrgM.Id=EM.OrgId 
			WHERE ISNULL(EM.IsOtherUser,0) = 0 AND  EM.StatusId =7  AND EM.EmployeeGroupId = 1 AND  EM.EmployeeId = @rSourceId 
			ORDER BY EmployeeName
			END
		END
	else
		BEGIN
		SELECT EM.EmployeeId as Id,
		[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title 
		FROM sHrm.vExtEmployee EM 
		INNER JOIN sSetup.vUserOrganization OM ON OM.Id = EM.OrgId INNER JOIN sSetup.tOrganizationMaster OrgM 
		ON OrgM.Id=EM.OrgId 
		WHERE ISNULL(IsOtherUser,0) = 0 AND  StatusId =7  AND EmployeeGroupId = 1 AND OM.OrgGroupId = @rOrgGroupId AND OM.UserId = @rUserId 
		ORDER BY EmployeeName
		END
	END TRY

	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [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,
	@rClassIds nvarchar(max) = '',
	@rDivisionIds nvarchar(max) = ''   
		
	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,
			SA.SUId AS SUId,
			CONVERT(Date,NULL) AS LeftDate -- For DataSet Refresh
			
	  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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					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='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			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(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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))
		AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  	
		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,
			SA.SUId AS SUId,
			SAD.LeftDate
			
	  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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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='')
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					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='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			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(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		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))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				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='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					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='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			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(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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)) 
		AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
		AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')	
		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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				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='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
					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='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
			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)
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			) 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)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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))
		 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
		 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		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
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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='') 
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
					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='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			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)
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			) 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)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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))
		 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
		 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					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='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			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(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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)
			AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		Order by SA.RollNo
	END

	ELSE IF(@rReportId=30232) -- Mantis : 0028532  #Start 
	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,
			SAD.LeftDate
	  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))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')  
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
					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='') 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
			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)
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			) 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)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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)) 
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		Order by SA.RollNo
	END -- #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,
			SAD.LeftDate
	  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))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')  
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
					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='') 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
			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)
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			) 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)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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)) 
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		Order by SA.RollNo
	END
	
	
	
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeAttendanceRegisterXMLInsert]...';


GO

ALTER PROCEDURE [sHrm].[pEmployeeAttendanceRegisterXMLInsert]
	
	@rStrXml nvarchar(MAX),
    @rOrgId int,
    @rAttendanceDate date='',
    @rCreatedUserId bigint,
    @rBatchId int=0,
	@rDepartmentId int=0
		
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
BEGIN TRANSACTION 
BEGIN
	DELETE EAR FROM sHrm.tEmployeeAttendanceRegister EAR
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EAR.EmployeeId
	INNER JOIN sHrm.vEmployeeCommonDetail  EJD ON EJD.EmployeeId = EM.Id
	WHERE EAR.AttendanceDate=@rAttendanceDate AND EAR.BatchId=@rBatchId AND ISNULL(EM.IsOtherUser,0) = 0 
	AND ((EJD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
	 
	 INSERT INTO sHrm.tEmployeeAttendanceRegister 
		(
			EmployeeId,	
			AttendanceDate,
			IsPresent,
			UpdatedUserId,
			UpdatedDateTime,
			AttendanceTagId,
			BatchId
			)
		SELECT	
		DISTINCT	
			EJD.EmployeeId,
			@rAttendanceDate,
			IsPresent,
			@rCreatedUserId,
			sCommon.fGetDate(),
			ISNULL(AttendanceTagId,0),
			@rBatchId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				EmployeeId bigint,
				IsPresent bit,
				AdmissionDate datetime,
				AttendanceTagId smallint,
				BatchId int
		   ) AS At
		   LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = At.EmployeeId
		   WHere (EJD.DateOfJoining <= @rAttendanceDate OR  ISNULL(EJD.DateOfJoining,'') = '')
		 AND ((EJD.DateOfLeaving > @rAttendanceDate) OR  ISNULL(EJD.DateOfLeaving,'') = '') 
        SELECT 1 AS Result
	 END	
		
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeCustomSearchGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pEmployeeCustomSearchGet]
(
	@rPageIndex int = null,
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'Number',
	@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) = '',
	@rEmployeeGroupId[nvarchar](50)='',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rLeftFromDate Date = '0001-01-01',
	@rLeftToDate Date = '9999-12-31',
	@rProbationUptoDate Date ,
	@rAhdocUptoDate Date ,
	@rPermanentDate Date ,
	@rDropDownStatusId int,
	
	@rNumber int = null,
	@rCustomTagId nvarchar(max) = '',
	@rDateOfResignation Date = '',
	@rIsOtherUser int=0,
	@rOrgGroupId int
 )
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Sql nvarchar(MAX)
	
	if @rDOBToDate = '9999-12-31'
	begin
		select @rDOBToDate = null
	end
	
	if @rLeftToDate = '9999-12-31'
	begin
		select @rLeftToDate = null
	end
	
	 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempEMP')
	 BEGIN		
		DROP Table sHrm.tTempEMP
	 END

	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	

	IF (@rCustomTagId <> '')
	BEGIN
		SELECT DISTINCT EM.Id AS EmployeeId1	
		INTO sHrm.tTempEMP
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeCustomTag ECT ON ECT.EmployeeId=EM.Id AND ISNULL(EM.IsOtherUser,0) = @rIsOtherUser 
		INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id
		WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0)) AND OM.OrgGroupId = @rOrgGroupId AND ISNULL(EM.IsOtherUser,0) = 0 AND (ISNULL(ECT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS EmployeeId1
		INTO sHrm.tTempEMP
	END



	SELECT * into sHrm.tTempEmployee1
	FROM sHrm.vEmployeeCustomSearch ECS 
	INNER JOIN sHrm.tTempEMP T2 ON ECS.EmployeeId = T2.EmployeeId1 OR @rCustomTagId = ''
	WHERE ((ECS.OrgId = @rOrgId) OR (@rOrgId = 0))
	AND ECS.OrgGroupId = @rOrgGroupId
	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
	AND ((ECS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
	AND ((ECS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
	AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
	AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
	AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))
	AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
	AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='')
	AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
	AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='')
	AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='')
	AND (ISNULL(ECS.EmployeeGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeGroupId,','))OR @rEmployeeGroupId='')
	AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
	AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
	AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='')
	AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
	AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((ECS.Number = @rNumber) OR (ISNULL(@rNumber,0) = 0))
	AND ((ECS.ProbationUptoDate = @rProbationUptoDate) OR (ISNULL(@rProbationUptoDate,'')=''))
	AND ((ECS.AhdocUptoDate = @rAhdocUptoDate) OR (ISNULL(@rAhdocUptoDate,'')=''))
	AND ((ECS.PermanentDate = @rPermanentDate) OR (ISNULL(@rPermanentDate,'')=''))
	AND ((ECS.DateofResignation = @rDateOfResignation) OR (ISNULL(@rDateOfResignation,'')=''))
	--AND ISNULL(ECS.IsOtherUser,0) = 0
	AND ISNULL(ECS.IsOtherUser,0) = @rIsOtherUser
	ORDER BY ECS.Number
	
	SET @rOrderBy=Replace(@rOrderBy,'Number','Number')
	Print @rOrderBy
	SET @sql='SELECT TE.EmployeeId,TE.Code AS Code
	,[sHrm].[fEmployeeNameGet](TE.FirstName , TE.MiddleName, TE.LastName, ISNULL(OM.EmployeeNameFormatId,1)) AS Name
	,TE.EmployeeType,TE.OrganizationDepartment AS OrganizationDepartment,
	StatusName FROM sHrm.tTempEmployee1 TE
	INNER JOIN sSetup.tOrganizationMaster OM ON TE.OrgId = OM.Id
	ORDER BY '+@rOrderBy
	exec(@Sql)
	
	create table #EMPLOYEETEMP
	(
		tid int identity(1,1)
		,t_EmployeeId bigint
		,EmployeeName nvarchar(300)
	)
	select @Sql = 'insert into #EMPLOYEETEMP
	SELECT TE.EmployeeId, [sHrm].[fEmployeeNameGet](TE.FirstName , TE.MiddleName, TE.LastName, ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName
	FROM sHrm.tTempEmployee1 TE
	INNER JOIN sSetup.tOrganizationMaster OM ON TE.OrgId = OM.Id
	ORDER BY ' + @rOrderBy
	
	exec (@Sql)
	
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	declare @lTotalRecords int,@lPageSize int = 10,@lResult nvarchar(max) = '',@lPaging varchar(max) = ''
	
	select @lTotalRecords = COUNT(*) FROM #EMPLOYEETEMP
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex, @lTotalRecords, @lPageSize)
	
	select @lResult = @lResult + '<tr><td><a style="cursor:pointer;" onclick="SelectEmp(' + convert(varchar,EmployeeId) + ',''' + isnull(Code,'') + ''')">Select</a></td>
	<td>' + isnull(Organization,'') + '</td><td>' + isnull(OrganizationDepartment,'') + '</td><td>' + isnull(Code,'') + '</td><td>' + isnull(EmployeeName,'') + '</td><td>' + isnull(EmployeeType,'') + '</td>
	<td>' + isnull(StatusName,'') + '</td></tr>'	
	from sHrm.tTempEmployee1,#EMPLOYEETEMP
	where t_EmployeeId = EmployeeId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	order by tid
	
	select @lResult as EmpList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP TABLE #EMPLOYEETEMP
	DROP Table sHrm.tTempEmployee1
	DROP Table sHrm.tTempEMP
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeGenerateReport]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeGenerateReport]	
	@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 = '',
	@rDOBToDate Date = '',
	@rDOJFromDate Date = '',
	@rDOJToDate Date = '',
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rIsCommonForOrg bit,
	@rLeftFromDate Date = '',
	@rLeftToDate Date = '',
	@rNumber int,
	@rProbationUptoDate Date = '',
	@rAhdocUptoDate Date = '',
	@rPermanentDate Date = '',
	@rCustomTagId nvarchar(max) = '',
	@rDateOfResignation Date = '',
	@rIsOtherUser int=0,
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION	
	
	--if @rColumnName <> ''
	--begin
	--	select @rColumnName = left(@rColumnName,len(@rColumnName)-1)
	--end
	
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate=''
	IF(@rDOJFromDate IS NULL)
		SET @rDOJFromDate=''
	IF(@rLeftFromDate IS NULL)
		SET @rLeftFromDate=''
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate=''
	IF(@rDOJToDate IS NULL)
		SET @rDOJToDate=''
	IF(@rLeftToDate ='9999-12-31 00:00:00')
		SET @rLeftToDate=''

	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	
		DECLARE @lNextNumber BIGINT 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		INSERT INTO sHrm.tEmployeeCustomSearch
			(
				Id,Title,ColumnName,OrgId,Code,FirstName,LastName,EmployeeTypeId,StatusId,OrganizationDepartmentId,ReligionId,
				MaritalStatusId,Qualification,GenderId,EmployeeDesignationId,BloodGroupId,DOBFromDate,DOBToDate,DOJFromDate,
				DOJToDate,IsCommon,CreatedUserId,CreatedDateTime,IsCommonForOrg,CustomTag,DropDownStatusId,OrderBy)
		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,@rCustomTagId,@rDropDownStatusId,@rOrderBy)
			--SELECT @lNextNumber AS Result
	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,
				@rCustomTagId=CustomTag,
				@rDropDownStatusId=ISNULL(DropDownStatusId,0),
				@rOrderBy=ISNULL(OrderBy,'Code')
				
		FROM
			sHrm.tEmployeeCustomSearch
		WHERE
			Id=@rId
	END
	
	DECLARE @Sql nvarchar(MAX)
	SET @rColumnName=Replace(@rColumnName,',ID No',',Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')

	SET @rColumnName=Replace(@rColumnName,',GR No',',Code')
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
 
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempEmployee')
	 BEGIN		
		DROP Table sHrm.tTempEmployee
	 END
	 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempEmployee13')
		 BEGIN
			DROP Table sHrm.tTempEmployee13
		 END
	 IF (@rCustomTagId <> '')
	BEGIN
		SELECT DISTINCT EM.Id AS EmployeeId1	
		INTO sHrm.tTempEmployee
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeCustomTag ECT ON ECT.EmployeeId=EM.Id  AND ISNULL(EM.IsOtherUser,0) = @rIsOtherUser 
		WHERE EM.OrgId = @rOrgId AND (ISNULL(ECT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS EmployeeId1
		INTO sHrm.tTempEmployee
	END

	--select * from sHrm.tTempEmployee
	
	 DECLARE @lAvailableEmployeeColumns nvarchar(max)=''
			DECLARE @lAvailableEmployeeCustomRes nvarchar(max)=''
			Declare @Title as nvarchar(max)
			DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
		
			SET @lAvailableEmployeeColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
								from sHrm.tEmployeeCustomFieldMaster PP  WHERE PP.OrgGroupId = @rOrgGroupId  
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
					--print @lAvailableEmployeeColumns
	        IF(@lAvailableEmployeeColumns IS NOT NULL)
	        BEGIN														
				set @query = 'SELECT  EmployeeId AS EmployeeId13 ,' + @lAvailableEmployeeColumns + ' into sHrm.tTempEmployee13 from 
					 (
						select PPE.FieldTitle,PP.EmployeeId,FieldData
						FROM
						sHrm.tEmployeeCustomFieldData PP 
							INNER JOIN sHrm.tEmployeeCustomFieldMaster PPE ON PPE.Id = PP.EmployeeCustomFieldId AND PPE.IsObsolete=0
							INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = PP.EmployeeId										
							WHERE EM.OrgId='''+convert(varchar(20),@rOrgId)+''' 
					) x 
					pivot 
					(
						Max(FieldData)
						for FieldTitle in (' +@lAvailableEmployeeColumns  + ')
					) p'
                execute(@query)

				SELECT  T13.*, ECS.OrgID, Organization, ECS.EmployeeId, ECS.Code, ECS.FirstName, ECS.MiddleName, ECS.LastName, 
				[sHrm].[fEmployeeNameGet](ECS.FirstName, ECS.MiddleName, ECS.LastName, ISNULL(OM.EmployeeNameFormatId,1)) AS Name,
				ECS.StatusId, ECS.StatusName, ECS.IsObsolete, ECS.EmployeeJobDetail, ECS.EmployeeDesignationId, ECS.EmployeeDesignation, 
				ECS.OrganizationDepartmentId, ECS.OrganizationDepartment, ECS.DateOfJoining, ECS.EmployeeTypeId, ECS.EmployeeType, ECS.EmployeeGroup, 
				ECS.DateOfLeaving, ECS.ReasonOfLeaving, ECS.Subjects, ECS.EmployeePersonalDetailId, ECS.UIDNumber, ECS.DateOfBirth, ECS.GenderId, 
				ECS.Gender, ECS.ReligionID, ECS.Religion, ECS.MaritalStatusID, ECS.MaritalStatus, ECS.IdentificationMark1, ECS.BloodGroupId, 
				ECS.BloodGroup, ECS.Qualification, ECS.FamilyCast, ECS.CastCategory, ECS.EmployeeGroupId, ECS.MobileNumber, ECS.PersonalEmail, 
				ECS.CompanyEmail, ECS.PhoneNoCompany, ECS.ExtensionNo, ECS.PresentStreetOne, ECS.PresentStreetTwo, ECS.PresentStreetThree, ECS.PresentCountry
				,ECS.PresentState, ECS.PresentCity, ECS.PresentZipCode, ECS.PresentContactNo, ECS.PermanentStreetOne, ECS.PermanentStreetTwo, 
				ECS.PermanentStreetThree, ECS.PermanentCountry, ECS.PermanentState, ECS.PermanentCity, ECS.PermanentZipCode, ECS.PermanentContactNo
				,ECS.EmergencyStreetOne, ECS.EmergencyStreetTwo, ECS.EmergencyStreetThree, ECS.EmergencyCountry, ECS.EmergencyState, ECS.EmergencyCity, 
				ECS.EmergencyZipCode, ECS.EmergencyContactNo, ECS.EPFNumber, ECS.ESINumber, ECS.AccountNumber, ECS.BankName, ECS.Branch, ECS.IFSCNumber
				,ECS.PanNumber, ECS.BasicPay, ECS.IncrementDate, ECS.EPFJoinDate, ECS.Payscale, ECS.AdhaarNumber, ECS.RetirementDate, ECS.Number,
				ECS.ProbationUptoDate, ECS.AhdocUptoDate, ECS.DateOfResignation, ECS.IsOtherUser, ECS.CustomTag, ECS.OrgGroupId, ECS.AccountHolderName, 
				ECS.WhatsAppContactNo, ECS.PunchId, ECS.ShiftName, ECS.PresentAddress
				into sHrm.tTempEmployee2
				FROM sHrm.vEmployeeCustomSearch ECS
				INNER JOIN sHrm.tTempEmployee T2 ON (ECS.EmployeeId = T2.EmployeeId1 OR @rCustomTagId = '')
				INNER JOIN sSetup.tOrganizationMaster OM ON ECS.OrgId = OM.Id			
				LEFT JOIN  sHrm.tTempEmployee13 T13 ON ECS.EmployeeId= T13.EmployeeId13
		
				WHERE
				 ((ECS.OrgId = @rOrgId) OR (@rOrgId = 0))
				 AND ECS.OrgGroupId = @rOrgGroupId
				AND ((ECS.Code Like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
				AND ((ECS.FirstName Like @rFirstName  + '%') OR (ISNULL(@rFirstName,'') = ''))	 			 
				AND ((ECS.LastName Like @rLastName + '%')OR(ISNULL(@rLastName,'') = ''))
				AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
				AND ((ISNULL(ECS.DateOfBirth,'') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
				AND ((ISNULL(ECS.DateOfBirth,'') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
				AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
				AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
				AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
				AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
				AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 			
				AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
				AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
				AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
				AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
				AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
				AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))			
				AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
				AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
				AND ((ECS.Number = @rNumber) OR (@rNumber=0))
				AND ((ECS.ProbationUptoDate = @rProbationUptoDate) OR (ISNULL(@rProbationUptoDate,'')=''))
				AND ((ECS.AhdocUptoDate = @rAhdocUptoDate) OR (ISNULL(@rAhdocUptoDate,'')=''))
				AND ((ECS.PermanentDate = @rPermanentDate) OR (ISNULL(@rPermanentDate,'')=''))
				AND ((ECS.DateOfResignation = @rDateOfResignation) OR (ISNULL(@rDateOfResignation,'')=''))
				AND ISNULL(ECS.IsOtherUser,0) = @rIsOtherUser 
 
				SET @sql=
				'SELECT '+
				@rColumnName+' 
				FROM sHrm.tTempEmployee2 ORDER BY '+@rOrderBy
				--SELECT @sql

				exec(@Sql)
		--print @Sql
				DROP Table sHrm.tTempEmployee2
				DROP Table sHrm.tTempEmployee
				DROP Table sHrm.tTempEmployee13
		END
		ELSE
		BEGIN
				SELECT  T13.*, ECS.OrgID, Organization, ECS.EmployeeId, ECS.Code, ECS.FirstName, ECS.MiddleName, ECS.LastName, 
				[sHrm].[fEmployeeNameGet](ECS.FirstName, ECS.MiddleName, ECS.LastName, ISNULL(OM.EmployeeNameFormatId,1)) AS Name,
				ECS.StatusId, ECS.StatusName, ECS.IsObsolete, ECS.EmployeeJobDetail, ECS.EmployeeDesignationId, ECS.EmployeeDesignation, 
				ECS.OrganizationDepartmentId, ECS.OrganizationDepartment, ECS.DateOfJoining, ECS.EmployeeTypeId, ECS.EmployeeType, ECS.EmployeeGroup, 
				ECS.DateOfLeaving, ECS.ReasonOfLeaving, ECS.Subjects, ECS.EmployeePersonalDetailId, ECS.UIDNumber, ECS.DateOfBirth, ECS.GenderId, 
				ECS.Gender, ECS.ReligionID, ECS.Religion, ECS.MaritalStatusID, ECS.MaritalStatus, ECS.IdentificationMark1, ECS.BloodGroupId, 
				ECS.BloodGroup, ECS.Qualification, ECS.FamilyCast, ECS.CastCategory, ECS.EmployeeGroupId, ECS.MobileNumber, ECS.PersonalEmail, 
				ECS.CompanyEmail, ECS.PhoneNoCompany, ECS.ExtensionNo, ECS.PresentStreetOne, ECS.PresentStreetTwo, ECS.PresentStreetThree, ECS.PresentCountry
				,ECS.PresentState, ECS.PresentCity, ECS.PresentZipCode, ECS.PresentContactNo, ECS.PermanentStreetOne, ECS.PermanentStreetTwo, 
				ECS.PermanentStreetThree, ECS.PermanentCountry, ECS.PermanentState, ECS.PermanentCity, ECS.PermanentZipCode, ECS.PermanentContactNo
				,ECS.EmergencyStreetOne, ECS.EmergencyStreetTwo, ECS.EmergencyStreetThree, ECS.EmergencyCountry, ECS.EmergencyState, ECS.EmergencyCity, 
				ECS.EmergencyZipCode, ECS.EmergencyContactNo, ECS.EPFNumber, ECS.ESINumber, ECS.AccountNumber, ECS.BankName, ECS.Branch, ECS.IFSCNumber
				,ECS.PanNumber, ECS.BasicPay, ECS.IncrementDate, ECS.EPFJoinDate, ECS.Payscale, ECS.AdhaarNumber, ECS.RetirementDate, ECS.Number,
				ECS.ProbationUptoDate, ECS.AhdocUptoDate, ECS.DateOfResignation, ECS.IsOtherUser, ECS.CustomTag, ECS.OrgGroupId, ECS.AccountHolderName, 
				ECS.WhatsAppContactNo, ECS.PunchId, ECS.ShiftName, ECS.PresentAddress
				into sHrm.tTempEmployee2
				FROM sHrm.vEmployeeCustomSearch ECS
				INNER JOIN sHrm.tTempEmployee T2 ON (ECS.EmployeeId = T2.EmployeeId1 OR @rCustomTagId = '')
				
				WHERE
				 ((ECS.OrgId = @rOrgId) OR (@rOrgId = 0))
				 AND ECS.OrgGroupId = @rOrgGroupId
				AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
				AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
				AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
				AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
				AND ((ISNULL(ECS.DateOfBirth,'') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
				AND ((ISNULL(ECS.DateOfBirth,'') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
				AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
				AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
				AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
				AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
				AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 			
				AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
				AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
				AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
				AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
				AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
				AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))			
				AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
				AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
				AND ((ECS.Number = @rNumber) OR (@rNumber=0))
				AND ((ECS.ProbationUptoDate = @rProbationUptoDate) OR (ISNULL(@rProbationUptoDate,'')=''))
				AND ((ECS.AhdocUptoDate = @rAhdocUptoDate) OR (ISNULL(@rAhdocUptoDate,'')=''))
				AND ((ECS.PermanentDate = @rPermanentDate) OR (ISNULL(@rPermanentDate,'')=''))
				AND ((ECS.DateOfResignation = @rDateOfResignation) OR (ISNULL(@rDateOfResignation,'')=''))
				AND ISNULL(ECS.IsOtherUser,0) = @rIsOtherUser 
 
				SET @sql=
				'SELECT '+
				@rColumnName+' 
				FROM sHrm.tTempEmployee2 ORDER BY '+@rOrderBy
				--SELECT @sql

				exec(@Sql)
		
				DROP Table sHrm.tTempEmployee2
				DROP Table sHrm.tTempEmployee
		END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, Error_Message()
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sHrm].[pHoliDayCountGet]...';


GO

ALTER PROCEDURE [sHrm].[pHoliDayCountGet]
	
	@rForMonth int=0,
	@rForYear int=0,
	@rBatchId int=0,
	@rOrgId int=0,
	--@rClassId int=0,
	@rEmployeeId bigint=0,
	@rDepartmentId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	CREATE table #Table1 (Id bigint identity,FromDate Date,ToDate Date,SourceId bigint,IsExists bit)
	
	CREATE table #Table2 (Id bigint identity,FromDate Date,ToDate Date,SourceId bigint)
	
	INSERT INTO #Table2 
						SELECT ES.FromDate,ES.ToDate,EA.SourceId FROM sActivity.tEventSchedule ES 
						INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id 
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
						INNER JOIN sHrm.vEmployeeCommunication EC ON EC.DepartmentId=DM.Id 				   
						WHERE ((ES.BatchId=@rBatchId)) 
						AND ((MONTH(ES.FromDate)<=@rForMonth) 
						AND (YEAR(ES.FromDate)=@rForYear))
						AND ((MONTH(ES.ToDate)>=@rForMonth) 
						AND (YEAR(ES.ToDate)=@rForYear)) 
						AND ES.IsHoliday=1 
						AND EA.SourceTypeId  = 2004
						AND ((EC.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
						GROUP BY ES.FromDate,ES.ToDate,EA.SourceId
					   
						UNION ALL
					   
						SELECT ES.FromDate,ES.ToDate,EA.SourceId FROM sActivity.tEventSchedule ES 
						INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id 			    
						INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId=EA.SourceId 
						WHERE ((ES.BatchId=@rBatchId)) 
						AND ((MONTH(ES.FromDate)<=@rForMonth) 
						AND (YEAR(ES.FromDate)=@rForYear))
						AND ((MONTH(ES.ToDate)>=@rForMonth) 
						AND (YEAR(ES.ToDate)=@rForYear)) 
						AND ES.IsHoliday=1 
						AND EA.SourceTypeId =95
						AND (EC.EmployeeId=@rEmployeeId OR (@rEmployeeId=0))
						GROUP BY ES.FromDate,ES.ToDate,EA.SourceId 
	  
	INSERT INTO #Table1 
	select FromDate,ToDate,Max(SourceId),0
	from
	( 
	SELECT case when MONTH(FromDate)=@rForMonth then FromDate
				when MONTH(FromDate)<>@rForMonth and MONTH(ToDate)=@rForMonth then DATEADD(DD,-Day(ToDate)+1,ToDate)
				when MONTH(FromDate)<@rForMonth and MONTH(ToDate)>@rForMonth then cast(rtrim(@rForYear *10000+ @rForMonth *100+ 01) as date) --mantis:28433
				else FromDate end as FromDate,
				ToDate,
				SourceId	
	From #Table2
	GROUP BY  FromDate,ToDate,SourceId
	)As Tmp
	GROUP BY  Tmp.FromDate,Tmp.ToDate,Tmp.SourceId
	--select * from #Table2 
	--select * from #Table1
	DECLARE @lTempCount int=0
	SELECT @lTempCount = count(Id) from #Table1
	WHILE @lTempCount > 0 
	BEGIN
		DECLARE @lFromDate Date,@lToDate Date

		SELECT @lFromDate = FromDate, @lToDate = ToDate FROM #Table1 WHERE Id=@lTempCount
		IF EXISTS(SELECT 1 FROM #Table1 WHERE Id <> @lTempCount AND ((@lFromDate between FromDate and ToDate) AND (@lToDate between FromDate and ToDate)))
		BEGIN
			UPDATE #Table1 SET IsExists = 1 WHERE Id = @lTempCount	
		END
		SET @lTempCount = @lTempCount - 1
	END
	 
	DECLARE @lCount int
	SELECT @lCount = count(Id) from #Table1
	DECLARE @lStatus nvarchar(5),@lFromYear int,@lFromMonth int,@lFromDay int,@lSourceId bigint,@lToYear int,@lToMonth int,@lToDay int
	DECLARE @lHoliDayCount int,@lBeginCount int ,@lEndCount int , @lTotalMonth int 
	SET @lHoliDayCount =0
	
		WHILE @lCount > 0 
					BEGIN
						SELECT
							@lFromYear = YEAR(FromDate),
							@lFromMonth = MONTH(FromDate),
							@lFromDay = DAY(FromDate),
							@lToYear = YEAR(ToDate),
							@lToMonth = MONTH(ToDate),
							@lToDay = DAY(ToDate),
							@lSourceId = SourceId,
							@lBeginCount = DAY(FromDate),
							@lEndCount = DAY(ToDate)
						FROM #Table1 T WHERE Id = @lCount AND IsExists = 0
					
						IF(@lFromDay = @lToDay  AND @lFromMonth = @lToMonth)
						BEGIN
							
							--SELECT @lStatus = [sAttendance].[fWeekHOffGet]
							--(@lFromYear,@lFromMonth,@lFromDay,@rBatchId,0,@lSourceId,'',@rOrgId)
							SELECT @lStatus = [sHrm].[fAttendanceWithLeaveGet](@lSourceId,@lFromYear,@lFromMonth,@lFromDay,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)
							IF(@lStatus = 'H')SET @lHoliDayCount=@lHoliDayCount+1
							
							
						END
						ELSE IF(@lFromDay != @lToDay)
						BEGIN
							IF(@lFromMonth = @lToMonth)
							BEGIN
								WHILE (@lBeginCount <= @lEndCount)
								BEGIN
								  
									--SELECT @lStatus = [sAttendance].[fWeekHOffGet] 	(@lFromYear,@lFromMonth,@lFromDay,@rBatchId,0,@lSourceId,'',@rOrgId)
									SELECT @lStatus = [sHrm].[fAttendanceWithLeaveGet](@lSourceId,@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)
									IF(@lStatus = 'H')
										SET @lHoliDayCount=@lHoliDayCount+1
									
									SET @lBeginCount = @lBeginCount +1	
							   END
							END
							ELSE
							BEGIN
								SET @lTotalMonth = @lToMonth - @lFromMonth
								 WHILE (@lTotalMonth > 0 AND @rForMonth=@lFromMonth)
								 BEGIN
									 DECLARE @lDays int = 0
									 SELECT @lDays = sCommon.fGetDaysInMonth(@lFromMonth,@lFromYear)
									 WHILE (@lBeginCount  <= @lDays)
									 BEGIN
										
										SELECT @lStatus = [sHrm].[fAttendanceWithLeaveGet](@lSourceId,@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)
										IF(@lStatus = 'H')
											SET @lHoliDayCount=@lHoliDayCount+1
											
										SET @lBeginCount = @lBeginCount +1
									END
									SET @lTotalMonth = @lTotalMonth-1
								 END
							END
						END
						SET @lCount = @lCount - 1
					END
	SELECT @lHoliDayCount
	DROP TABLE #Table1
	DROP TABLE #Table2
END
GO
PRINT N'Altering Procedure [sHrm].[pImportUser]...';


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

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

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

	SET @tmp = ''
	SET @tmp1 =''
	
	SELECT @tmp = @tmp + T.EmployeeCode  + ', '  from #tTable1 T 
	LEFT JOIN  sHrm.tEmployeeMaster EM ON T.EmployeeCode  = EM.Code 
	AND EM.OrgId = @rOrgId 
	WHERE EM.ID IS NULL AND T.EmployeeCode <> '' AND ISNULL(EM.IsOtherUser,0) = 0 AND upper(T.UserType) = 'EMPLOYEE' 
 
	SELECT @tmp1 = @tmp1 + T.EmployeeCode  + ', '  from #tTable1 T 
	LEFT JOIN  sStudent.tStudentMaster SM ON T.EmployeeCode  = SM.Code 
	AND SM.OrgId = @rOrgId  
	WHERE SM.ID IS NULL AND T.EmployeeCode <> '' AND upper(T.UserType) = 'STUDENT'

	IF @tmp <> ''
	BEGIN
		SELECT -101 AS Result, SUBSTRING(@tmp, 0, LEN(@tmp)) AS ResultDetail
		RETURN
	END

	IF @tmp1 <> ''
	BEGIN
		SELECT -102 AS Result, SUBSTRING(@tmp1, 0, LEN(@tmp1)) AS ResultDetail
		RETURN
	END

	SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
	BEGIN		
		SELECT         
			@lUserType = UserType ,
			@lEmployeeCode = EmployeeCode,
			@lUserName = UserName,
			@lDisplayName = DisplayName,
			@lPassword = [Password],
			@lRole = [Role],
			@lRoleId = RoleId
		FROM #tTable1 WHERE Id = @lCount    
	     
		IF UPPER(@lUserType) = 'EMPLOYEE'
		BEGIN
		 SELECT @rUserSourceId = Id FROM sHrm.tEmployeeMaster WHERE Code = @lEmployeeCode AND OrgID=@rOrgId AND ISNULL(IsOtherUser,0) = 0
		 SELECT @rUserSourceTypeId = 95
		END

		ELSE IF(UPPER(@lUserType) = 'STUDENT')
		BEGIN
			SELECT @rUserSourceId = Id FROM sStudent.tStudentMaster WHERE Code = @lEmployeeCode AND OrgID=@rOrgId 
			SELECT @rUserSourceTypeId =2003
		END

		ELSE
		BEGIN
			 SELECT @rUserSourceId = 0
			 SELECT @rUserSourceTypeId = 1
		END

		-- Added 'AND SourceTypeId=@rUserSourceTypeId AND SourceId <> @rUserSourceId' for mantis 0027721 by foram 
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE OrgId = @rOrgId AND LoginTitle=@lUserName AND SourceTypeId=@rUserSourceTypeId AND SourceId <> @rUserSourceId)							
		BEGIN
			Select -103 As Result, 'User Name Already Exist for Code ' + @lEmployeeCode  As ResultDetail
			return
		END
		-- Commented for mantis 0027721 by foram
		--IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE OrgId = @rOrgId AND SourceTypeId=@rUserSourceTypeId AND SourceId = @rUserSourceId)							
		--BEGIN
		--	Select -104 As Result, 'User Already Exist for Code ' + @lEmployeeCode As ResultDetail
		--	return
		--END

		-- Uncommented for mantis 0027721 by foram
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceId = @rUserSourceId AND OrgId=@rOrgId AND SourceTypeId=@rUserSourceTypeId)--AND LoginTitle = @lUserName )
		BEGIN
			UPDATE sSecurity.tUser
			SET	
				LoginPassword = @lPassword,				
				IsObsolete = 0,			
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				LoginTitle = @lUserName,
				DisplayTitle = @lDisplayName
			WHERE 
				SourceId = @rUserSourceId AND OrgId=@rOrgId	AND SourceTypeId=@rUserSourceTypeId  --AND LoginTitle = @lUserName		
		END
		ELSE
		BEGIN
			DECLARE @lNextNumber BIGINT	
			EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 101, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sSecurity.tUser
				(
					Id,		
					DisplayTitle,
					LoginTitle,
					LoginPassword,
					LastLockOutDate,
					NumberOfLogonAttempt,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime,
					OrgId,
					SourceId,
					SourceTypeId	
				)
			VALUES
				(
					@lNextNumber,
					@lDisplayName,					
					@lUserName,
					@lPassword,
					sCommon.fGetDate(),
					0,
					0,
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rOrgId,
					@rUserSourceId,
					@rUserSourceTypeId
				)
				
			IF NOT EXISTS(Select 1 From [sSecurity].[tUserRole]  WHERE RoleId = @lRoleId AND UserId=@lNextNumber)
			BEGIN
				INSERT INTO 
				[sSecurity].[tUserRole] (RoleId, UserId, IsObsolete, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsPrimary)
				VALUES
				(@lRoleId,@lNextNumber,0,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),1)
			END
		END
		SET @lCount = @lCount-1
	  END 
	SELECT 1 AS Result, '' AS ResultDetail
 END
END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmpLeavePresence]...';


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

BEGIN 
       SELECT 	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			@rIsDetail AS IsDetail,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,   
			EM.EmployeeId,
			EM.DepartmentName,
			EM.EmployeeGrade,      
			ISNULL(LB.BalanceLeave,0) AS BalanceLeave,
			ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays,
			 ISNULL(AT.LWP,0) AS LWP,
			 CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
			LTM.Id AS LeaveTypeId,	
			LTM.Title AS LeaveType,
			(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) AS NoOfLeave,
	   		(
			SELECT ISNULL(SUM(L.NoOfLeave),0)				 
			FROM 
				sHrm.tLeave L
				INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
				AND IsLWP = 1 AND StatusId=550
			WHERE 
				L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
				AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
				AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
				AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
				AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    	        AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
	   	    ) AS LWPNoOfLeave,
		   	ISNULL(LTM.IsLWP,0) AS IsLWP,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) < @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) AS UptoNoOfLeave,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 1 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) < @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) AS LWPUptoNoOfLeave,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) AS CurrentNoOfLeave,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 1 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0)
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')='')) 
		   	) AS LWPCurrentNoOfLeave,
			EM.Number,
			EWD.WorkingDays AS EmployeeWorkingDay	--add for 27636 mantis

        FROM
			sHrm.vEmployeeCommonDetail EM
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0
			LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EM.EmployeeId AND LTM.Id = LB.LeaveTypeId AND LB.BatchId=@rBatchId
			INNER JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.OrgId=EM.OrgID AND EM.EmployeeGradeId = EGM.Id 
			LEFT JOIN sHrm.tWorkingDays WD ON WD.EmployeeGradeId = EGM.Id AND WD.ForYear = @rForYear AND WD.forMonth = @rForMonth
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForYear = @rForYear AND AT.forMonth = @rForMonth
			LEFT JOIN sHrm.tEmployeeWorkingDays EWD ON EWD.EmployeeId=EM.EmployeeId AND EWD.BatchId=@rBatchId AND EWD.ForYear=@rForYear AND EWD.ForMonth =@rForMonth	--add for 27636 mantis
			
    	WHERE
    		EM.OrgID = @rOrgId 
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
			AND EM.IsOtherUser = 0
    		ORDER BY EM.Code
    		
END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmployeeLeaveDetailsGet]...';


GO

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

BEGIN 



       SELECT 
				 @rBuilder1 AS Builder1,
				 @rBuilder2 AS Builder2, 
				 EM.Code AS EmployeeCode,
				 EM.EmployeeName,   
				 EM.EmployeeId,
				 EM.DepartmentName,
				 EM.EmployeeGrade,      
				 --ISNULL(AT.LWP,0) AS LWP,
				 --CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
				 --MM.Title AS MonthName,
		   --      (SELECT  t1.MonthTitle FROM (SELECT MonthTitle,MonthNumber FROM [sSetup].[fMonthYearForBatchGet] (100100001))  AS T1
				 --WHERE MonthNumber = 4) AS MonthName,
				 --(SELECT  t2.YearNumber FROM (SELECT YearNumber,MonthNumber FROM [sSetup].[fMonthYearForBatchGet] (100100001))  AS T2
				 --WHERE YearNumber = 2014 AND MonthNumber = 4 ) AS YearName,
				 --AT.ForYear As YearName,
				 L.LeaveReason,
				 L.NoOfLeave,
				 L.ReportDate,
				 L.FromDate,
				 L.ToDate,
				 LPM.Title As LeavePeriod,
				 LTM.Title As LeaveType,
				 LTM.IsCarryForward,
				 LTM.IsLWP,
				 ISNULL(SM.Title,'') AS StatusName,
				 OM.Title AS OrganizationTitle,
				 ISNULL(OM.StreetOne,'') AS StreetOne,
				 ISNULL(OM.StreetTwo,'')AS StreetTwo,
				 ISNULL(OM.StreetThree,'')AS StreetThree,
				 ISNULL(OM.CityName,'')AS CityName,
				 ISNULL(OM.StateName,'')AS StateName,
				 ISNULL(OM.CountryName,'')AS CountryName,
				 ISNULL(OM.ZipCode,'')AS ZipCode,
				 ISNULL(EM.EmployeeDesignation,'')AS EmployeeDesignation ,
				 ISNULL(LM.BalanceLeave,0) AS TotalLeave ,
				 ISNULL(EC.MobileNumber,'')AS MobileNumber,
				 ISNULL((SELECT    
						SUM(NoOfLeave) AS UsedLeave
					FROM 
						sHrm.tLeave L1  
					WHERE 
						(L1.EmployeeId = EM.EmployeeId) 
						AND (L1.LeaveTypeId = L.LeaveTypeId)      
						AND BatchId = @rBatchId AND L.OrgId = @rOrgId 
						AND L1.StatusId = 550 -- apporved
						GROUP BY L1.EmployeeId,L1.LeaveTypeId),0) AS UsedLeave -- Mantis : 0027600

        FROM 
				sHrm.vEmployeeCommonDetail EM 
		--LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
		--LEFT JOIN sCommon.tMonthMaster MM ON MM.Id=AT.ForMonth
		INNER JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id=L.LeavePeriodId
		INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id=L.LeaveTypeId
		LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		--INNER JOIN sHrm.tLeaveBalance LM ON LM.EmployeeId = EM.EmployeeId 
		LEFT JOIN sHrm.tLeaveBalance LM ON LM.EmployeeId = EM.EmployeeId AND LM.BatchId = L.BatchId AND LM.LeaveTypeId = L.LeaveTypeId
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
    	WHERE 
    	EM.OrgID = @rOrgId 
    	AND L.BatchId=@rBatchId
    	AND (YEAR(L.FromDate) = @rForYear OR @rForYear='') 
    	AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth='') 
    	AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    	AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    	AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    	AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    	AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    	AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    	AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
    	AND ((L.LeaveReason Like '%'+@rLeaveReson+'%' ) OR (ISNULL(@rLeaveReson,'')=''))
    	AND ((L.StatusId=@rStatusId) OR (@rStatusId=0))
    	AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
		AND ((LM.LeaveTypeId=@rLeaveTypeId) OR (@rLeaveTypeId=0))
END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseOrderApprovedGet]...';


GO








ALTER PROCEDURE [sPurchase].[pPurchaseOrderApprovedGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select PO.Id,
			   PO.RefNumber,
			   PO.PurchaseRequestId,
			   PO.RequestedBy,
			   PO.StatusId,
			   PO.VendorId,
			   PO.LocationId,
			   PO.OrgGroupId,
			   PO.PODate,
			   PO.BillToAddress,
			   PO.ShipToAddress,
			   PO.RequiredBy,
			   ISNULL(SM.Title,'') as Status,
			   VM.Code AS VendorCode,
			   VM.Title AS VendorName,
			   PR.Number As PurchaseNumber 
		from   [sPurchase].[tPurchaseOrder] PO(nolock) 
			   Left Join [sPurchase].[tPurchaseRequest] PR ON PR.ID = PO.PurchaseRequestId
			   Left JOIN sProcurement.tVendorMaster  VM on PO.VendorId = VM.ID 
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
		where  PO.Id=@rId AND PO.IsObsolete = 0 AND PO.StatusId = 3

		select POD.Id,
			   POD.PurchaseOrderId,
			   POD.OrgGroupId,
			   POD.PurchaseRequestDetailId,
			   POD.StockItemId,
			   POD.TotalQty,
			   POD.Remark, 
			   SUMa.Id AS UnitTypeId,
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tPurchaseOrderDetail] POD (nolock)
			   Inner JOIN	sPurchase.tPurchaseOrder PO	ON PO.Id = POD.PurchaseOrderId AND PO.IsObsolete = 0 AND PO.StatusId = 3
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = POD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  PurchaseOrderId=@rId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseOrderGet]...';


GO








ALTER PROCEDURE [sPurchase].[pPurchaseOrderGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select PO.Id,
			   PO.RefNumber,
			   PO.PurchaseRequestId,
			   PO.RequestedBy,
			   PO.StatusId,
			   PO.VendorId,
			   PO.LocationId,
			   PO.OrgGroupId,
			   PO.PODate,
			   PO.BillToAddress,
			   PO.ShipToAddress,
			   PO.RequiredBy,
			   ISNULL(SM.Title,'') as Status,
			   VM.Code AS VendorCode,
			   VM.Title AS VendorName 
		from   [sPurchase].[tPurchaseOrder] PO(nolock) 
			   Left JOIN sProcurement.tVendorMaster  VM on PO.VendorId = VM.ID
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
		where  PO.Id = @rId AND PO.IsObsolete = 0

		select POD.Id,
			   POD.PurchaseOrderId,
			   POD.PurchaseRequestDetailId,
			   POD.OrgGroupId,
			   POD.StockItemId,
			   POD.TotalQty,
			   POD.Remark, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Id					AS UnitTypeId,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tPurchaseOrderDetail] POD (nolock)
			   Inner JOIN	sPurchase.tPurchaseOrder PO	ON PO.Id = POD.PurchaseOrderId AND PO.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = POD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  POD.PurchaseOrderId = @rId

		select  AutoId,
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl
		from    sPurchase.tDocumentManagement
		where   SourceId = @rId and SourceTypeId = 2042
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseOrderSearchGet]...';


GO



ALTER PROCEDURE [sPurchase].[pPurchaseOrderSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				PO.Id,
				PO.PurchaseRequestId,
				PO.RefNumber as Number,
				PO.RequestedBy, 
				PO.LocationId, 
				PO.PODate,
				ISNULL(SM.Title,'') as Status
		FROM		
				sPurchase.tPurchaseOrder PO (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on PO.StatusId = SM.Id
		WHERE 
				((PO.RefNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((PO.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PO.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND PO.IsObsolete = 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseRequestApprovedGet]...';


GO







ALTER PROCEDURE [sPurchase].[pPurchaseRequestApprovedGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select PR.Id,
			   PR.Number,
			   PR.RequestedBy,
			   PR.StatusId,
			   PR.VendorId,
			   PR.LocationId,
			   PR.BranchId,
			   PR.OrgGroupId,
			   PR.ResourceId,
			   PR.RequestDate,
			   PR.RequiredBy,
			   ISNULL(SM.Title,'') as Status,
			   VM.Code AS VendorCode,
			   VM.Title AS VendorName 
		from   [sPurchase].[tPurchaseRequest] PR (nolock) 
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = PR.StatusId
			   Left Join sProcurement.tVendorMaster  VM on PR.VendorId = VM.ID
		where  PR.Id=@rId AND PR.IsObsolete = 0 AND PR.StatusId = 3

		select PRD.Id,
			   PRD.PurchaseRequestId,
			   PRD.OrgGroupId,
			   PRD.StockItemId,
			   PRD.RequestedQty,
			   PRD.Remark, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tPurchaseRequestDetail] PRD (nolock)
			   Inner JOIN	sPurchase.tPurchaseRequest PR	ON PR.Id = PRD.PurchaseRequestId AND PR.IsObsolete = 0 AND PR.StatusId = 3
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  PurchaseRequestId=@rId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseRequestGet]...';


GO


ALTER PROCEDURE [sPurchase].[pPurchaseRequestGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  PR.Id,
				PR.Number,
				PR.RequestedBy,
				PR.StatusId,
				PR.VendorId,
				PR.LocationId,
				PR.BranchId,
				PR.OrgGroupId,
				PR.ResourceId,
				PR.RequestDate,
				PR.RequiredBy,
				ISNULL(SM.Title,'') as Status,
				VM.Code AS VendorCode,
				VM.Title AS VendorName
		from    [sPurchase].[tPurchaseRequest] PR (nolock) 
			    Left Join sProcurement.tVendorMaster  VM on PR.VendorId = VM.ID
				Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = PR.StatusId
		where   PR.Id=@rId AND PR.IsObsolete = 0

		select PRD.Id,
			   PRD.PurchaseRequestId,
			   PRD.OrgGroupId,
			   PRD.StockItemId,
			   PRD.RequestedQty,
			   PRD.Remark, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tPurchaseRequestDetail] PRD (nolock)
			   Inner JOIN	sPurchase.tPurchaseRequest PR	ON PR.Id = PRD.PurchaseRequestId AND PR.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  PurchaseRequestId=@rId

		select  AutoId,
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl
		from    sPurchase.tDocumentManagement
		where   SourceId = @rId and SourceTypeId = 2040
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseRequestSearchGet]...';


GO


ALTER PROCEDURE [sPurchase].[pPurchaseRequestSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				PR.Id, 
				PR.Number,
				PR.RequestedBy, 
				PR.LocationId, 
				PR.RequestDate,
				ISNULL(SM.Title,'') as Status
		FROM		
				sPurchase.tPurchaseRequest PR (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on PR.StatusId = SM.Id
		WHERE 
				((PR.Number like @rNumber+'%') OR (@rNumber = ''))
   				AND ((PR.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND PR.IsObsolete = 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Creating Procedure [sPurchase].[pQualityCheckAdd]...';


GO




CREATE PROCEDURE [sPurchase].[pQualityCheckAdd]
		@rId bigint,
		@rGoodsReceivedNoteId bigint,
		@rPurchaseOrderId bigint,
		@rRequestedBy nvarchar(100),
		@rOrgGroupId int,
		@rLocationId int,
		@rStatusId smallint,	
		@rUserId bigint,
		@rDetailList sPurchase.QualityCheckDetailType READONLY,
		@rDocumentList sPurchase.DocumentManagementType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tQualityCheck
			set 
				StatusId = @rStatusId,
				GoodsReceivedNoteId = @rGoodsReceivedNoteId,
				PurchaseOrderId = @rPurchaseOrderId,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tQualityCheckDetail
			where QualityCheckId = @rId

			DECLARE @lNextNumberQCD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQualityCheckDetail',@lNextNumber = @lNextNumberQCD output
			set @lNextNumberQCD=@lNextNumberQCD-1
			INSERT INTO sPurchase.tQualityCheckDetail
			(
				Id,
				OrgGroupId,
				QualityCheckId,
				GoodsReceivedNoteDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				AcceptedQty,
				RejectedQty,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberQCD+Id,
					OrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberQCD=@lNextNumberQCD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQualityCheckDetail', @rCurrentNumber = @lNextNumberQCD

			INSERT INTO sPurchase.tDocumentManagement
			(
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl,
				CreatedUserId,
				CreatedDateTime
			)
			select	@rOrgGroupId,
					@rId,
					2045, 
					@rUserId,
					FileName,
					Size,
					DocumentUrl,
					@rUserId, 
					GETUTCDATE() 
			from @rDocumentList
			select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQualityCheck',@lNextNumber = @lNextNumber output	
			---------------select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			---------------@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tQualityCheck
			(
				Id,
				QCNumber,
				GoodsReceivedNoteId,
				PurchaseOrderId,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rGoodsReceivedNoteId,
				@rPurchaseOrderId,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberQCDD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQualityCheckDetail',@lNextNumber = @lNextNumberQCDD output	
			set @lNextNumberQCDD=@lNextNumberQCDD-1

	 		INSERT INTO sPurchase.tQualityCheckDetail
			(
				Id,
				OrgGroupId,
				QualityCheckId,
				GoodsReceivedNoteDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				AcceptedQty,
				RejectedQty,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberQCDD+Id,
					OrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberQCDD=@lNextNumberQCDD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQualityCheckDetail', @rCurrentNumber = @lNextNumberQCDD
			
			INSERT INTO sPurchase.tDocumentManagement
			(
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl,
				CreatedUserId,
				CreatedDateTime
			)
			select	@rOrgGroupId,
					@rId,
					2045, 
					@rUserId,
					FileName,
					Size,
					DocumentUrl,
					@rUserId, 
					GETUTCDATE() 
			from @rDocumentList
			select @rId
			--select 1;
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pQualityCheckSearchGet]...';


GO


ALTER PROCEDURE [sPurchase].[pQualityCheckSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				QC.Id,
				--GRN.PurchaseRequestId,
				--GRN.PurchaseOrderId,
				--GRN.DepartmentBranchId,
				--GRN.VendorId,
				QC.QCNumber as Number,
				QC.RequestedBy, 
				QC.LocationId,
				ISNULL(SM.Title,'') as Status
		FROM		
				sPurchase.tQualityCheck QC (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on QC.StatusId = SM.Id
		WHERE 
				((QC.QCNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((QC.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((QC.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND QC.IsObsolete = 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pQuotationRequestGet]...';


GO


ALTER PROCEDURE [sPurchase].[pQuotationRequestGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select QR.Id,
			   QR.Number,
			   QR.PurchaseRequestId,
			   QR.Name,
			   QR.StatusId,
			   QR.VendorId,
			   QR.LocationId,
			   QR.BranchId,
			   QR.OrgGroupId,
			   QR.RFQDate,
			   QR.Description,
			   QR.StartDate,
			   QR.EndDate,
			   QR.BidOpen,
			   QR.BidClose,
			   QR.PersonContact,
			   QR.Email,
			   QR.SendToVendor,
			   QR.VendorId,
			   ISNULL(SM.Title,'') as Status,
			   VM.Code AS VendorCode,
			   VM.Title AS VendorName,
			   PR.Number as PurchaseNumber
		from   [sPurchase].[tQuotationRequest] QR(nolock) 
			   Left JOIN sProcurement.tVendorMaster  VM on QR.VendorId = VM.ID
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = QR.StatusId
			   Left Join [sPurchase].[tPurchaseRequest] PR on PR.Id = QR.PurchaseRequestId

		where  QR.Id=@rId AND QR.IsObsolete = 0

		select QRD.Id,
			   QRD.QuotationRequestId,
			   QRD.PurchaseRequestDetailId,
			   QRD.OrgGroupId,
			   QRD.StockItemId,
			   QRD.RequestedQty,
			   QRD.TargetPrice,
			   QRD.Remark, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tQuotationRequestDetail] QRD (nolock)
			   Inner JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId AND QR.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  QRD.QuotationRequestId=@rId

		select  AutoId,
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl
		from    sPurchase.tDocumentManagement
		where   SourceId = @rId and SourceTypeId = 2041
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Altering Procedure [sPurchase].[pQuotationRequestSearchGet]...';


GO


ALTER PROCEDURE [sPurchase].[pQuotationRequestSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				QR.Id, 
				QR.Number,
				QR.Name, 
				QR.LocationId,
				ISNULL(SM.Title,'') as Status
		FROM		
				sPurchase.tQuotationRequest QR (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on QR.StatusId = SM.Id
		WHERE 
				((QR.Number like @rNumber+'%') OR (@rNumber = ''))
   				AND ((QR.Name like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((QR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND QR.IsObsolete = 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pSalesReturnSearchGet]...';


GO


ALTER PROCEDURE [sPurchase].[pSalesReturnSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				SR.Id,
				SR.SRNumber as Number,
				SR.RequestedBy, 
				SR.LocationId,
				ISNULL(SM.Title,'') as Status
		FROM		
				sPurchase.tSalesReturn SR (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on SR.StatusId = SM.Id
		WHERE 
				((SR.SRNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((SR.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((SR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND SR.IsObsolete = 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sStudent].[ppImportStudent_Update_Dynamicly]...';


GO
ALTER proc [sStudent].[ppImportStudent_Update_Dynamicly]
@rOrgId int,
@rCreatedUserId bigint,
@rCode nvarchar(20) = '', 
@rFirstName nvarchar(100) = '',
@rMiddleName nvarchar(100) = '',
@rLastName nvarchar(100) = '',
@rGender nvarchar(20) = '',
@rAdmissionStandard nvarchar(100) = '',
@rAdmissionCategory nvarchar(100) = '',
@rAdmissionYear nvarchar(10) = '',
@rAdmissionDate datetime = '',
@rLeftStandard nvarchar(100) = '',
@rLeftDate datetime = '',
@rLeftYear nvarchar(10) = '',
@rLeftReason nvarchar(200) = '',
@rPreviousSchool nvarchar(200) = '',
@rDateOfBirth datetime = '',
@rBirthPlace nvarchar(150) = '',
@rBloodGroup nvarchar(20) = '',
@rBirthTaluka nvarchar(150) = '',
@rBirthDistrict nvarchar(150) = '',
@rFamilySubCast nvarchar(100) = '',
@rFamilyCast nvarchar(100) = '',
@rCastCatagory nvarchar(50) = '',
@rMotherTongue nvarchar(100) = '',
@rNationality nvarchar(50) = '',
@rReligion nvarchar(50) = '',
@rHobby nvarchar(50) = '',
@rFatherName nvarchar(100)='',
@rFatherContactNo nvarchar(50)='',
@rFatherDateOfBirth datetime = '',
@rFatherOccupation nvarchar(50)='',
@rFatherQualification nvarchar(50)='',
@rFatherMail nvarchar(50)='',
@rFatherOfficeAddress nvarchar(500)='',
@rFatherIncome int=0,
@rMotherDateOfBirth datetime = '',
@rMothername nvarchar(100)='',
@rMotherContactNo nvarchar(50)='',
@rMotherOccupation nvarchar(50)='',
@rMotherQualification nvarchar(50)='',
@rMotherMail nvarchar(50)='',
@rMotherOfficeAddress nvarchar(100)='',
@rMotherIncome int=0,
@rRelationshipName nvarchar(100)='',
@rRelativeName nvarchar(100)='',
@rRelativeDateOfBirth datetime='',
@rRelativeOccupation nvarchar(50)='',
@rRelativeQualification	nvarchar(50)='',
@rRelativeContactNo	nvarchar(50)='',
@rRelativeMail nvarchar(50)='',
@rRelativeOfficeAddress nvarchar(500)='',
@rRelativeIncome int=0,
@rPresentStreetOne nvarchar(150)='',
@rPresentStreetTwo nvarchar(150)='',
@rPresentStreetThree nvarchar(150)='',
@rPresentCity nvarchar(50)='',
@rPresentZipCode nvarchar(20)='',
@rPresentState nvarchar(50)='',
@rPresentCountry nvarchar(50)='',
@rPresentContactNo nvarchar(20)='', 
@rParentEmail nvarchar(50)='',
@rStudentContactNo  nvarchar(50)='',
@rStudentEmail nvarchar(50)='', 
@rAccountNumber nvarchar(20)='',
@rBankName nvarchar(100)=0,
@rBranch nvarchar(100)='', 
@rBankIFSCCode  nvarchar(20)='',
@rAdhaarNumber nvarchar(20)='',
@rValidate varchar(250)='' ,
@rOrgGroupId int,
@rBirthState  nvarchar(150)='',
@rUIDNumber nvarchar(50)='', 
@rBirthCountry nvarchar(150)='',
@rFatherOfficeContactNo nvarchar(50)='',
@rMotherOfficeContactNo varchar(50)='',
@rWhatsAppContactNo nvarchar(20)='',
@rPreviousLeftDate datetime = ''
as
begin	
	IF(@rAdmissionDate='') 
	SET @rAdmissionDate = NULL
	IF(@rDateOfBirth='') 
	SET @rDateOfBirth = NULL
	IF(@rFatherDateOfBirth='') 
	SET @rFatherDateOfBirth = NULL
	IF(@rMotherDateOfBirth='') 
	SET @rMotherDateOfBirth = NULL
	IF(@rRelativeDateOfBirth='') 
	SET @rRelativeDateOfBirth = NULL
	IF(@rPreviousLeftDate='') 
	SET @rPreviousLeftDate = NULL
	
	declare @StudentId bigint = 0
	select @StudentId = Id from sStudent.tStudentMaster where Code = @rCode and OrgID = @rOrgId
	select @StudentId = isnull(@StudentId,0)
	
	declare @genderid int,@AdmissionStandardid int,@LeftStandardid int,@nationalityid int,@religionid int, 
	 @castcategoryid int,@admissioncategoryid int,@bloodgroupid int 
	
	select @rGender = case when upper(@rGender) = 'M' then 'Male'
	when  upper(@rGender) = 'MALE' then 'Male'
	when upper(@rGender) ='FEMALE' then 'Female'
	when upper(@rGender) = 'F' then 'Female' when upper(@rGender) = 'N' then 'Not Known' else 'Not Known' end
	 
	select @genderid = isnull(Id,0) from sCommon.tGenderMaster where Title = @rGender
	
	select @AdmissionStandardid = isnull(Id,0) from sSetup.tClassMaster where Title = @rAdmissionStandard and OrgId = @rOrgId
 
	select @LeftStandardid = isnull(Id,0) from sSetup.tClassMaster where Title = @rLeftStandard and OrgId = @rOrgId
	
	select @nationalityid = isnull(Id,0) from sCommon.tCountryMaster where Nationality = @rNationality and OrgGroupId = @rOrgGroupId
	 
	 select @religionid = isnull(Id,0) from sCommon.tReligionMaster where Title = @rReligion  and OrgGroupId = @rOrgGroupId
	 
	  select @castcategoryid = isnull(Id,0) from sCommon.tCastCategoryMaster where Title = @rcastcatagory and OrgGroupId = @rOrgGroupId
	  
	  select @admissioncategoryid = isnull(Id,0) from sStudent.tAdmissionCategoryMaster where Title = @radmissioncategory and OrgGroupId = @rOrgGroupId
	 
	 select @bloodgroupid = isnull(Id,0) from sCommon.tBloodGroupMaster  where Title = @rBloodGroup  
	  
	select @genderid = isnull(@genderid,0),@AdmissionStandardid = isnull(@AdmissionStandardid,0),@LeftStandardid = isnull(@LeftStandardid,0),
	@nationalityid = isnull(@nationalityid,0),@religionid = isnull(@religionid,0),@castcategoryid = isnull(@castcategoryid,0),
	@admissioncategoryid = isnull(@admissioncategoryid,0),@bloodgroupid = isnull(@bloodgroupid,0) 
	
	declare @lNextNumber bigint,@Title varchar(100)=''
	
	 
	 
	if @rFirstName <> ''
	select @rFirstName = [sSetup].[fPortalXMLTagsReplaceReverse](@rFirstName)
	if @rMiddleName <> ''
	select @rMiddleName = [sSetup].[fPortalXMLTagsReplaceReverse](@rMiddleName)
	if @rLastName <> ''
	select @rLastName = [sSetup].[fPortalXMLTagsReplaceReverse](@rLastName)
	 if @rAdmissionDate <> ''
	select @rAdmissionDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdmissionDate)
	 if @rAdmissionYear <> ''
	select @rAdmissionYear = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdmissionYear)
	 if @rLeftDate <> ''
	select @rLeftDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rLeftDate)
	if @rLeftYear <> ''
	select @rLeftYear= [sSetup].[fPortalXMLTagsReplaceReverse](@rLeftYear)
	if @rLeftReason <> ''
	select @rLeftReason= [sSetup].[fPortalXMLTagsReplaceReverse](@rLeftReason)
	if @rPreviousSchool <> ''
	select @rPreviousSchool= [sSetup].[fPortalXMLTagsReplaceReverse](@rPreviousSchool)
	if @rDateOfBirth <> ''
	select @rDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rDateOfBirth)
	if @rBirthPlace <> ''
	select @rBirthPlace= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthPlace)
	if @rBirthTaluka<> ''
	select @rBirthTaluka= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthTaluka)
	if @rBirthDistrict <> ''
	select @rBirthDistrict= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthDistrict)
	if @rFamilyCast <> ''
	select @rFamilyCast= [sSetup].[fPortalXMLTagsReplaceReverse](@rFamilyCast)
	if @rFamilySubCast <> ''
	select @rFamilySubCast= [sSetup].[fPortalXMLTagsReplaceReverse](@rFamilySubCast)
	if @rMotherTongue <> ''
	select @rMotherTongue= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherTongue)
	if @rHobby <> ''
	select @rHobby= [sSetup].[fPortalXMLTagsReplaceReverse](@rHobby)
	if @rFatherName<> ''
	select @rFatherName= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherName)
	if @rFatherContactNo<> ''
	select @rFatherContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherContactNo)
	if @rFatherDateOfBirth<> ''
	select @rFatherDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherDateOfBirth)
	if @rFatherOccupation<> ''
	select @rFatherOccupation= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherOccupation)
	if @rFatherQualification<> ''
	select @rFatherQualification= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherQualification)
	if @rFatherMail<> ''
	select @rFatherMail= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherMail)
	if @rFatherOfficeAddress<> ''
	select @rFatherOfficeAddress= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherOfficeAddress)
	if @rFatherIncome<> ''
	select @rFatherIncome= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherIncome)
	if @rMothername<> ''
	select @rMothername= [sSetup].[fPortalXMLTagsReplaceReverse](@rMothername)
	if @rMotherContactNo<> ''
	select @rMotherContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherContactNo)
	if @rMotherDateOfBirth<> ''
	select @rMotherDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherDateOfBirth)
	if @rMotherOccupation<> ''
	select @rMotherOccupation= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherOccupation)
	if @rMotherQualification <> ''
	select @rMotherQualification= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherQualification)
	if @rMotherMail<> ''
	select @rMotherMail= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherMail)
	if @rMotherOfficeAddress<> ''
	select @rMotherOfficeAddress= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherOfficeAddress)
	if @rMotherIncome<> ''
	select @rMotherIncome= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherIncome)
	if @rRelationshipName <> ''
	select @rRelationshipName= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelationshipName)
	if @rRelativeName <> ''
	select @rRelativeName= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeName)
	if @rRelativeDateOfBirth <> ''
	select @rRelativeDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeDateOfBirth)
	if @rRelativeOccupation <> ''
	select @rRelativeOccupation= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeOccupation)
	if @rRelativeQualification <> ''
	select @rRelativeQualification= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeQualification)
	if @rRelativeContactNo<> ''
	select @rRelativeContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeContactNo)
	if @rRelativeMail<> ''
	select @rRelativeMail= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeMail)
	if @rRelativeOfficeAddress <> ''
	select @rRelativeOfficeAddress= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeOfficeAddress)
	if @rRelativeIncome <> ''
	select @rRelativeIncome= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeIncome)
	 
	if @rPresentStreetOne <> ''
	select @rPresentStreetOne = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetOne)
	if @rPresentStreetTwo <> ''
	select @rPresentStreetTwo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetTwo)
	if @rPresentStreetThree <> ''
	select @rPresentStreetThree = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetThree)
	 
	if @rPresentZipCode <> ''
	select @rPresentZipCode = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentZipCode)
	if @rPresentState <> ''
	select @rPresentState = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentState)
	if @rPresentCountry <> ''
	select @rPresentCountry = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCountry)
	if @rPresentCity <> ''
	select @rPresentCity = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCity)
	if @rPresentContactNo <> ''
	select @rPresentContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentContactNo)
	if @rPresentState <> ''
	select @rPresentState = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentState)
	if @rAccountNumber <> ''
	select @rAccountNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAccountNumber)
	if @rBankName <> ''
	select @rBankName = [sSetup].[fPortalXMLTagsReplaceReverse](@rBankName)
	if @rBranch <> ''
	select @rBranch = [sSetup].[fPortalXMLTagsReplaceReverse](@rBranch)
	if @rParentEmail<> ''
	select @rParentEmail = [sSetup].[fPortalXMLTagsReplaceReverse](@rParentEmail)
	if @rUIDNumber <> ''
	select @rUIDNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rUIDNumber)
	if @rAdhaarNumber <> ''
	select @rAdhaarNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdhaarNumber)
	  if @rStudentContactNo <> ''
	select @rStudentContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rStudentContactNo)
	if @rStudentEmail <> ''
	select @rStudentEmail= [sSetup].[fPortalXMLTagsReplaceReverse](@rStudentEmail)
	if @rBankIFSCCode <> ''
	select @rBankIFSCCode = [sSetup].[fPortalXMLTagsReplaceReverse](@rBankIFSCCode)
	if @rBirthState<> ''
	select @rBirthState= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthState)
	if @rBirthCountry<> ''
	select @rBirthCountry= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthCountry)
	if @rFatherOfficeContactNo<> ''
	select @rFatherOfficeContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherOfficeContactNo)
	if @rMotherOfficeContactNo<> ''
	select @rMotherOfficeContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherOfficeContactNo)
	if @rWhatsAppContactNo<> ''
	select @rWhatsAppContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rWhatsAppContactNo)

	 if @rPreviousLeftDate <> ''
	select @rPreviousLeftDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rPreviousLeftDate)
	
	begin

		UPDATE sStudent.tStudentMaster
		SET 
		FirstName = case when isnull(@rFirstName,'') <> '' then @rFirstName else FirstName end
		,MiddleName   = case when isnull(@rMiddleName,'') <> '' then @rMiddleName else MiddleName end
		,LastName     = case when isnull(@rLastName,'') <> '' then @rLastName else LastName end
		--,StatusId     = case when isnull(@statusid,0) <> 0 then @statusid else StatusId end
		 ,UpdatedUserId = @rCreatedUserId
		,UpdatedDateTime = sCommon.fGetDate()
		WHERE Id = @StudentId and OrgId = @rOrgId
		
		IF NOT EXISTS(Select * from sStudent.tStudentAdmission where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentAdmission(StudentId,CreatedUserId,CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

		SELECT @rLeftDate,@LeftStandardid			
		UPDATE sStudent.tStudentAdmission
		SET 
			AdmissionStandardId = case when isnull(@AdmissionStandardid,0) <> 0 then @AdmissionStandardid else AdmissionStandardId end,	 
			AdmissionYear = case when isnull(@rAdmissionYear,0) <> 0 then @rAdmissionYear else AdmissionYear end,			
			AdmissionDate = case when isnull(@rAdmissionDate,'') <> '' then @rAdmissionDate else AdmissionDate end,
			LeftStandardId =	case when isnull(@LeftStandardid,'') <> '' then @LeftStandardid else LeftStandardId end,
			LeftDate = case when isnull(@rLeftDate,'') <> '' then @rLeftDate else LeftDate end,	 
			LeftYear = case when isnull(@rLeftYear,0) <> 0 then @rLeftYear else LeftYear end,
			LeftReason = case when isnull(@rLeftReason,'') <> '' then @rLeftReason else LeftReason end,
			PreviousSchool = case when isnull(@rPreviousSchool,'') <> '' then @rPreviousSchool else PreviousSchool end,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			PreviousLeftDate = case when isnull(@rPreviousLeftDate,'') <> '' then @rPreviousLeftDate else PreviousLeftDate end
		WHERE StudentId = @StudentId 
	 

		IF NOT EXISTS(Select * from sStudent.tStudentOther where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentOther (StudentId, CreatedUserId, CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

		Update sStudent.tStudentOther
		set  
		GenderId = case when isnull(@genderid,0) <> 0 then @genderid else GenderId  end,
		ReligionId =  case when isnull(@religionId,0) <> 0 then @religionId else ReligionId  end,
		 BloodGroupId =  case when isnull(@bloodgroupid,0) <> 0 then @bloodgroupid else BloodGroupId  end,
		DateOfBirth =  case when isnull(@rDateOfBirth,'') <> '' then @rDateOfBirth else DateOfBirth  end,
		BirthPlace = case when isnull(@rBirthPlace,'') <> '' then @rBirthPlace else BirthPlace  end,
		BirthTaluka = case when isnull(@rBirthTaluka,'') <> '' then @rBirthTaluka else BirthTaluka  end,
			BirthDistrict = case when isnull(@rBirthDistrict,'') <> '' then @rBirthDistrict else BirthDistrict  end,
		 UIDNumber =  case when isnull(@rUIDNumber,'') <> '' then @rUIDNumber else UIDNumber  end,
		UpdatedUserId = @rCreatedUserId,
		UpdatedDateTime = sCommon.fGetDate(),
		FamilyCast =case when isnull(@rFamilyCast,'') <> '' then @rFamilyCast else FamilyCast  end,
		AdhaarNumber =case when isnull(@rAdhaarNumber,'') <> '' then @rAdhaarNumber else AdhaarNumber  end,
		FamilySubCast = case when isnull(@rFamilySubCast,'') <> '' then @rFamilySubCast else FamilySubCast  end,
		MotherTongue = case when isnull(@rMotherTongue,'') <>'' then @rMotherTongue else MotherTongue  end,
		NationalityId = case when isnull(@NationalityId,0) <> 0 then @NationalityId else NationalityId  end,
		 Hobby = case when isnull(@rHobby,'') <> '' then @rHobby else Hobby  end,
		CastCategoryId =case when isnull(@castcategoryid,0) <> 0 then @castcategoryid else CastCategoryId  end,
			BirthState = case when isnull(@rBirthState,'') <> '' then @rBirthState else BirthState  end,
				BirthCountry = case when isnull(@rBirthCountry,'') <> '' then @rBirthCountry else BirthCountry  end
		where StudentId = @StudentId 
		
	
		IF NOT EXISTS(Select * from sStudent.tStudentFamily where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentFamily (StudentId, CreatedUserId, CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

  		UPDATE sStudent.tStudentFamily
		SET 
	      
		   FatherName = case when isnull(@rFatherName,'') <> '' then @rFatherName else FatherName end 
		  ,FatherDateOfBirth =  case when isnull(@rFatherDateOfBirth,'') <> '' then @rFatherDateOfBirth else FatherDateOfBirth end 
		  ,FatherOccupation = case when isnull(@rFatherOccupation,'') <> '' then @rFatherOccupation else FatherOccupation end 
		  ,FatherQualification = case when isnull(@rFatherQualification,'') <> '' then @rFatherQualification else FatherQualification end 
		  ,FatherContactNo =  case when isnull(@rFatherContactNo,'') <> '' then @rFatherContactNo else FatherContactNo end 
		  ,FatherMail =  case when isnull(@rFatherMail,'') <> '' then @rFatherMail else FatherMail end 
		  ,FatherOfficeAddress = case when isnull(@rFatherOfficeAddress,'') <> '' then @rFatherOfficeAddress else FatherOfficeAddress end 
		  ,FatherIncome = case when isnull(@rFatherIncome,'') <> '' then @rFatherIncome else FatherIncome end 
		  ,MotherName = case when isnull(@rMotherName,'') <> '' then @rMotherName else MotherName end  
		  ,MotherDateOfBirth =  case when isnull(@rMotherDateOfBirth,'') <> '' then @rMotherDateOfBirth else MotherDateOfBirth  end   
		  ,MotherOccupation =  case when isnull(@rMotherOccupation,'') <> '' then @rMotherOccupation else MotherOccupation  end   
		  ,MotherQualification =  case when isnull(@rMotherQualification,'') <> '' then @rMotherQualification else MotherQualification  end      
		   ,MotherContactNo = case when isnull(@rMotherContactNo,'') <> '' then @rMotherContactNo else MotherContactNo end
		   ,MotherMail = case when isnull(@rMotherMail,'') <> '' then @rMotherMail else MotherMail end
		   ,MotherOfficeAddress = case when isnull(@rMotherOfficeAddress,'') <> '' then @rMotherOfficeAddress else MotherOfficeAddress end
		   ,MotherIncome = case when isnull(@rMotherIncome,'') <> '' then @rMotherIncome else MotherIncome end
		   ,RelationshipName = case when isnull(@rRelationshipName,'') <> '' then @rRelationshipName else RelationshipName end
		   ,RelativeName = case when isnull(@rRelativeName,'') <> '' then @rRelativeName else RelativeName end
			,RelativeDateOfBirth = case when isnull(@rRelativeDateOfBirth,'') <> '' then @rRelativeDateOfBirth else RelativeDateOfBirth end 
			,RelativeOccupation = case when isnull(@rRelativeOccupation,'') <> '' then @rRelativeOccupation else RelativeOccupation end 
			,RelativeQualification = case when isnull(@rRelativeQualification,'') <> '' then @rRelativeQualification else RelativeQualification end 
			,RelativeContactNo = case when isnull(@rRelativeContactNo,'') <> '' then @rRelativeContactNo else RelativeContactNo end 
			,RelativeMail = case when isnull(@rRelativeMail,'') <> '' then @rRelativeMail else RelativeMail end 
			,RelativeOfficeAddress = case when isnull(@rRelativeOfficeAddress,'') <> '' then @rRelativeOfficeAddress else RelativeOfficeAddress end 
			,RelativeIncome = case when isnull(@rRelativeIncome,'') <> '' then @rRelativeIncome else RelativeIncome end 
			,FatherOfficeContactNo = case when isnull(@rFatherOfficeContactNo,'') <> '' then @rFatherOfficeContactNo else FatherOfficeContactNo end 
			,MotherOfficeContactNo = case when isnull(@rMotherOfficeContactNo,'') <> '' then @rMotherOfficeContactNo else MotherOfficeContactNo end 
		  ,[UpdatedUserId] = @rCreatedUserId
		  ,[UpdatedDateTime] =  sCommon.fGetDate() 
		WHERE StudentId = @StudentId
			

		IF NOT EXISTS(Select * from sStudent.tStudentCommunication where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentCommunication (StudentId, CreatedUserId, CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

  		UPDATE sStudent.tStudentCommunication
		SET 
	      
		   [PresentStreetOne] = case when isnull(@rPresentStreetOne,'') <> '' then @rPresentStreetOne else [PresentStreetOne] end 
		  ,[PresentStreetTwo] =  case when isnull(@rPresentStreetTwo,'') <> '' then @rPresentStreetTwo else [PresentStreetTwo] end 
		  ,[PresentStreetThree] = case when isnull(@rPresentStreetThree,'') <> '' then @rPresentStreetThree else [PresentStreetThree] end 
		  ,[PresentCountry] = case when isnull(@rPresentCountry,'') <> '' then @rPresentCountry else [PresentCountry] end 
		  ,[PresentState] =  case when isnull(@rPresentState,'') <> '' then @rPresentState else [PresentState] end 
		  ,[PresentCity] =  case when isnull(@rPresentCity,'') <> '' then @rPresentCity else [PresentCity] end 
		  ,PresentZipCode = case when isnull(@rPresentZipCode,'') <> '' then @rPresentZipCode else PresentZipCode end 
		  ,PresentContactNo = case when isnull(@rPresentContactNo,'') <> '' then @rPresentContactNo else PresentContactNo end 
		  ,ParentEmail = case when isnull(@rParentEmail,'') <> '' then @rParentEmail else ParentEmail end  
		  ,StudentContactNo =  case when isnull(@rStudentContactNo,'') <> '' then @rStudentContactNo else StudentContactNo  end   
		  ,StudentEmail =  case when isnull(@rStudentEmail,'') <> '' then @rStudentEmail else StudentEmail  end   
		   ,[UpdatedUserId] = @rCreatedUserId
		  ,[UpdatedDateTime] =  sCommon.fGetDate() 
		  ,WhatsAppContactNo =  case when isnull(@rWhatsAppContactNo,'') <> '' then @rWhatsAppContactNo else WhatsAppContactNo  end   
		WHERE StudentId = @StudentId
		

		IF NOT EXISTS(Select * from sStudent.tStudentAdditional where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentAdditional (StudentId) Values (@StudentId)
		END

		UPDATE sStudent.tStudentAdditional
		SET
			BankBranch = case when isnull(@rBranch,'') <> '' then @rBranch else BankBranch end 
		  ,BankAccountNumber = case when isnull(@rAccountNumber,'') <> '' then @rAccountNumber else BankAccountNumber end 
		  ,BankName = case when isnull(@rBankName,'') <> '' then @rBankName else BankName end 
		  ,BankIFSCCode = case when isnull(@rBankIFSCCode,'') <> '' then @rBankIFSCCode else BankIFSCCode end 
		  
		where StudentId=@StudentId
		
	end	
end
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentPastLCVerificationGet]...';


GO
ALTER PROCEDURE [sStudent].[pRptStudentPastLCVerificationGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgId int,
	 @rBatchId int,
	 @rDepartmentId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
     @rStrCode nvarchar(20)='',
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rPreviousSchool nvarchar(200)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 BEGIN

	     SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,	
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
            vSA.ClassId AS ClassId,
			CM.OrderIndex AS ClassOrderIndex,
			vSA.ClassId AS DivisionId,	
			DM.OrderIndex AS DivisionOrderIndex,		
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,		
			vSA.AcademicId,
			vSA.Code,
			ISNULL(SA.AdmissionNumber,'') As OldGRNo,
            vSA.FirstName,vSA.MiddleName,vSA.LastName,
			[sStudent].[fStudentNameGet](vSA.FirstName , vSA.MiddleName, vSA.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SO.DateOfBirth,'') AS DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			ISNULL(SA.PreviousStandard,'') AS PreviousStandard,
			ISNULL(SA.LeftDate,'') AS LeftDate,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SA.PreviousLCNumber,'') AS PreviousLCNumber,
			ISNULL(SA.PreviousLCDate,'') AS PreviousLCDate,
			ISNULL(SA.PreviousLCResult,'') AS PreviousLCResult,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			ISNULL(SA.PreviousLeftDate,'') AS PreviousLeftDate,		--add for 27789 mantis
			(CASE WHEN @rPreviousSchool='' THEN 'All'
				ELSE SA.PreviousSchool END) AS PreviousSchool,		--add for 28188 mantis
			--SA.PreviousSchool
			ISNULL(RM.Title,'') AS Religion
	FROM 
		    sStudent.vStudentAcademic vSA 	
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
		    LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId = RM.Id	--Mantis : 0028286
	Where		
	           ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
	       AND ((vSA.BatchId=@rBatchId) OR (@rBatchId=0))
	       AND ((vSA.DepartmentId=@rDepartmentId) OR(@rDepartmentId=0))
	       AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))	  
	       AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))	
		   AND (ISNULL(vSA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')
           AND ((vSA.StatusId=@rStatusId)OR(@rStatusId=0))
		   AND ((vSA.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		   --AND (ISNULL(SA.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')	
		    AND ((SA.PreviousSchool =  @rPreviousSchool) OR (@rPreviousSchool='')) 
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentAdmissionAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentAdmissionAdd] @rStudentId BIGINT
	,@rPreviousSchool NVARCHAR(200)
	,@rPreviousSchoolTypeId INT
	,@rPreviousStudentId BIGINT
	,@rAdmissionFormId BIGINT
	,@rAdmissionFormNumber NVARCHAR(20)
	,@rAdmissionStandardId INT
	,@rAdmissionDate DATE
	,@rAdmissionYear NVARCHAR(10)
	,@rLeftStandardId INT
	,@rLeftDate DATE
	,@rLeftYear NVARCHAR(10)
	,@rInactiveDate DATE
	,@rInActiveReason NVARCHAR(200)
	,@rLeftReason NVARCHAR(200)
	,@rLCProgress NVARCHAR(200)
	,@rLCConduct NVARCHAR(200)
	,@rLCBook NVARCHAR(20)
	,@rLCNumber NVARCHAR(20)
	,@rLCDate DATE
	,@rLCRemark NVARCHAR(200)
	,@rLCCopy TINYINT
	,@rLcId BIGINT
	,@rBatchId INT
	,@rCreatedUserId BIGINT
	,@rUpdatedUserId BIGINT
	,@rIsGeneral BIT
	,@rAdmissionNumber NVARCHAR(50) = ''
	,@rIsTransfer BIT = 0
	,@rTransferFrom NVARCHAR(150) = ''
	,@rPassingYear NVARCHAR(20) = ''
	,@rIsTFWS BIT = 0
	,@rIsCertificateHolder BIT = 0
	,@rCertificateName NVARCHAR(100) = ''
	,@rAdmissionQuotaId INT = 0
	,@rPreviousStandard NVARCHAR(50) = ''
	,@rAcademicId BIGINT = 0
	,@rPreviousLCDate DATE = NULL
	,@rPreviousLCNumber NVARCHAR(100) = ''
	,@rPreviousLCResult NVARCHAR(100) = ''
	,@rProofOfDOB NVARCHAR(200) = ''
	,@rPreviousLeftDate DATE = NULL --add for 27789 mantis
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRANSACTION

		IF (@rIsGeneral = 1)
		BEGIN
			IF NOT EXISTS (
					SELECT *
					FROM sStudent.tStudentAdmission
					WHERE StudentId = @rStudentId
					)
			BEGIN
				INSERT INTO sStudent.tStudentAdmission (
					StudentId
					,PreviousSchool
					,AdmissionStandardId
					,AdmissionDate
					,LeftStandardId
					,LeftDate
					,InactiveDate
					,BatchId
					,CreatedUserId
					,CreatedDateTime
					,PreviousStandard
					,PreviousLCNumber
					,PreviousLCDate
					,PreviousLCResult
					,ProofOfDOB
					,PreviousLeftDate
					)
				VALUES (
					@rStudentId
					,@rPreviousSchool
					,@rAdmissionStandardId
					,@rAdmissionDate
					,@rLeftStandardId
					,@rLeftDate
					,@rInactiveDate
					,@rBatchId
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rPreviousStandard
					,@rPreviousLCNumber
					,@rPreviousLCDate
					,@rPreviousLCResult
					,@rProofOfDOB
					,@rPreviousLeftDate
					)

				SELECT 1 AS Result
			END
			ELSE
			BEGIN
				UPDATE sStudent.tStudentAdmission
				SET AdmissionStandardId = @rAdmissionStandardId
					,AdmissionDate = @rAdmissionDate
					,LeftStandardId = @rLeftStandardId
					,LeftDate = @rLeftDate
					,InactiveDate = @rInactiveDate
					,PreviousLeftDate = @rPreviousLeftDate
					,UpdatedUserId = @rUpdatedUserId
					,UpdatedDateTime = sCommon.fGetDate()
				WHERE StudentId = @rStudentId
			END

			SELECT 11 AS Result
		END
		ELSE
		BEGIN
			IF (@rIsGeneral = 0)
				IF NOT EXISTS (
						SELECT *
						FROM sStudent.tStudentAdmission
						WHERE StudentId = @rStudentId
						)
				BEGIN
					INSERT INTO sStudent.tStudentAdmission (
						StudentId
						,PreviousSchool
						,PreviousSchoolTypeId
						,PreviousStudentId
						,AdmissionFormId
						,AdmissionFormNumber
						,AdmissionStandardId
						,AdmissionDate
						,AdmissionYear
						,LeftStandardId
						,LeftDate
						,LeftYear
						,InactiveDate
						,InActiveReason
						,LeftReason
						,LCProgress
						,LCConduct
						,LCBook
						,LCNumber
						,LCDate
						,LCRemark
						,LCCopy
						,LcId
						,BatchId
						,CreatedUserId
						,CreatedDateTime
						,AdmissionNumber
						,IsTransfer
						,TransferFrom
						,PassingYear
						,IsTFWS
						,IsCertificateHolder
						,CertificateName
						,AdmissionQuotaId
						,PreviousStandard
						,PreviousLCNumber
						,PreviousLCDate
						,PreviousLCResult
						,ProofOfDOB
						,PreviousLeftDate --add for 27789 mantis
						)
					VALUES (
						@rStudentId
						,@rPreviousSchool
						,@rPreviousSchoolTypeId
						,@rPreviousStudentId
						,@rAdmissionFormId
						,@rAdmissionFormNumber
						,@rAdmissionStandardId
						,@rAdmissionDate
						,@rAdmissionYear
						,@rLeftStandardId
						,@rLeftDate
						,@rLeftYear
						,@rInactiveDate
						,@rInActiveReason
						,@rLeftReason
						,@rLCProgress
						,@rLCConduct
						,@rLCBook
						,@rLCNumber
						,@rLCDate
						,@rLCRemark
						,@rLCCopy
						,@rLcId
						,@rBatchId
						,@rCreatedUserId
						,sCommon.fGetDate()
						,@rAdmissionNumber
						,@rIsTransfer
						,@rTransferFrom
						,@rPassingYear
						,@rIsTFWS
						,@rIsCertificateHolder
						,@rCertificateName
						,@rAdmissionQuotaId
						,@rPreviousStandard
						,@rPreviousLCNumber
						,@rPreviousLCDate
						,@rPreviousLCResult
						,@rProofOfDOB
						,@rPreviousLeftDate --add for 27789 mantis
						)

					SELECT 1 AS Result
				END
				ELSE
				BEGIN
					UPDATE sStudent.tStudentAdmission
					SET PreviousSchool = @rPreviousSchool
						,PreviousSchoolTypeId = @rPreviousSchoolTypeId
						,PreviousStudentId = @rPreviousStudentId
						,AdmissionFormId = @rAdmissionFormId
						,AdmissionFormNumber = @rAdmissionFormNumber
						,AdmissionStandardId = @rAdmissionStandardId
						,AdmissionDate = @rAdmissionDate
						,AdmissionYear = @rAdmissionYear
						,LeftStandardId = @rLeftStandardId
						,LeftDate = @rLeftDate
						,LeftYear = @rLeftYear
						,InactiveDate = @rInactiveDate
						,InActiveReason = @rInActiveReason
						,LeftReason = @rLeftReason
						,LCProgress = @rLCProgress
						,LCConduct = @rLCConduct
						,LCBook = @rLCBook
						,LCNumber = @rLCNumber
						,LCDate = @rLCDate
						,LCRemark = @rLCRemark
						,LCCopy = @rLCCopy
						,LcId = @rLcId
						,UpdatedUserId = @rUpdatedUserId
						,UpdatedDateTime = sCommon.fGetDate()
						,AdmissionNumber = @rAdmissionNumber
						,IsTransfer = @rIsTransfer
						,TransferFrom = @rTransferFrom
						,PassingYear = @rPassingYear
						,IsTFWS = @rIsTFWS
						,IsCertificateHolder = @rIsCertificateHolder
						,CertificateName = @rCertificateName
						,AdmissionQuotaId = @rAdmissionQuotaId
						,PreviousStandard = @rPreviousStandard
						,PreviousLCNumber = @rPreviousLCNumber
						,PreviousLCDate = @rPreviousLCDate
						,PreviousLCResult = @rPreviousLCResult
						,ProofOfDOB = @rProofOfDOB
						,PreviousLeftDate = @rPreviousLeftDate --add for 27789 mantis
					WHERE StudentId = @rStudentId
				END

			SELECT 11 AS Result
		END

		UPDATE A
		SET ClassStatusId = 3
		FROM sStudent.tAcademic A
		INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
		INNER JOIN sStudent.tStudentAdmission SA ON A.StudentId = SA.StudentId
			AND A.ClassId = SA.LeftStandardId
		WHERE SM.StatusId = 3
			AND SM.Id = @rStudentId

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT - 1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentFullProfileGet]...';


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


GO
ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,1) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	DivisionIncharge,
	IsBreak,
	IsBreakBefore,
	EmployeeSubject,
	ClassSubject,
	EmployeeSNSubject,
	ISNULL(Convert(smallint,(select Isnull(max(cast(IsBreak as smallint)),0)*2+ISNULL(max(cast(IsBreakBefore as smallint)),0)*1
			From sTimetable.tTimeTableTime
			where TimeTableSchemaId=@rTimeTableSchemaId AND LectureNumber=A.LactureNumber
			Group by TimeTableSchemaId,LectureNumber)),0) AS HideBreak,
	A.ShortName
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(EM.LastName+' '+EM.FirstName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,'') As FromTime,
	ISNULL(TTM.ToTime,'') As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	(SELECT ISNULL(EM.FirstName+' '+EM.LastName,'') FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tDivisionMaster DIE ON DIE.InchargeEmployeeId = EM.Id  WHERE DIE.Id = DV.Id) as DivisionIncharge,

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

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

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


GO
ALTER PROCEDURE [sTimetable].[pTimeTableListGet]
	   
	  @rBatchId int,
	  @rEmployeeId bigint,
	  @rDayId smallint,
	  @rLectureNo smallint,
	  @rTimeTableSchemaId int,
	   @rOrgId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN    
	SELECT 	 
	TT.Id AS TimeTableID,
	DV.Title AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	ISNULL(Em.FirstName,'') + ' '+ISNULL(em.LastName,'') AS EmployeeName,  
	ISNULL(EM.ShortName,'') AS EmpShortName,
	ISNULL(SM.Title,'') AS Subject,
	TT.DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),LectureNumber),'') AS DayLacture,
	ISNULL(CL.Id,0) AS ClassId,
	--ISNULL(CL.Title,'')+ISNULL(DV.Title,'') AS ClassDivisionName
    ISNULL(DV.Code,'') AS ClassDivisionName
	--(Select ClassId From sSetup.vBatchClassDivision BCD WHERE BCD.DivisionId = DV.Id AND BatchId = @rBatchId) AS ClassId,
	--(Select ClassDivisionName From sSetup.vBatchClassDivision BCD WHERE BCD.DivisionId = DV.Id AND BatchId = @rBatchId) AS ClassDivisionName
  
	FROM 
	sTimetable.tTimeTable TT  
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	INNER JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	INNER JOIN sSetup.tClassMaster CL ON CL.Id = DV.ClassId
	--LEFT JOIN sSetup.vBatchClassDivision BCD ON BCD.DivisionId = DV.Id --AND BatchId = @rBatchId
	
	WHERE
	 TT.TimeTableSchemaId=@rTimeTableSchemaId 
	AND((EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
	  AND ((TT.DayId = @rDayId) OR (@rDayId = 0))
	  AND ((LectureNumber = @rLectureNo) OR (@rLectureNo = 0))
	   AND ((DV.OrgId=@rOrgId) OR (@rOrgId=0))
	   AND  ISNULL(EM.IsOtherUser,0) = 0
    --AND ClassId IN (sCommon.fGetIntIdForOrg(8,9999),sCommon.fGetIntIdForOrg(9,9999))  
	--order by DivisionId 
	order by LectureNumber
END
GO
PRINT N'Altering Procedure [sWf].[pWfApprovingAuthorityAdd]...';


GO




ALTER PROCEDURE [sWf].[pWfApprovingAuthorityAdd]
		@rId [int],
		@rAuthoritySourceTypeId [smallint],
		@rAuthoritySourceId [bigint],
		@rOrgId [smallint],
		@rWfFunctionalityId [smallint]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId = 0)
		BEGIN
			INSERT INTO sWf.tWfApprovingAuthority
			(
			AuthoritySourceTypeId,
			AuthoritySourceId,
			OrgId,
			WfFunctionalityId
			)
			VALUES
			(
			@rAuthoritySourceTypeId,
			@rAuthoritySourceId,
			@rOrgId,
			@rWfFunctionalityId
			)
			SET @rId = SCOPE_IDENTITY()
			SELECT @rId
		END
		ELSE
		BEGIN
			DELETE FROM sWf.tWfApprovingAuthority
			WHERE OrgId = @rOrgId AND WfFunctionalityId = @rWfFunctionalityId
			AND AuthoritySourceTypeId = @rAuthoritySourceTypeId

			INSERT INTO sWf.tWfApprovingAuthority
			(
			AuthoritySourceTypeId,
			AuthoritySourceId,
			OrgId,
			WfFunctionalityId
			)
			VALUES
			(
			@rAuthoritySourceTypeId,
			@rAuthoritySourceId,
			@rOrgId,
			@rWfFunctionalityId
			)
			SET @rId = SCOPE_IDENTITY()
			SELECT @rId
		END
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Altering Procedure [sWf].[pWfRoleGet]...';


GO



ALTER PROCEDURE [sWf].[pWfRoleGet]
	  @rOrgGroupId smallint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select Id,
			   Title as DisplayTitle
	    from   sSecurity.tRole (nolock)
		where  IsObsolete='0' AND OrgGroupId = @rOrgGroupId
          AND  Id <> ([sCommon].[fGetIntIdForOrg](21,@rOrgGroupId)) 
		  AND  Id <> ([sCommon].[fGetIntIdForOrg](22,@rOrgGroupId))
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Altering Procedure [sWf].[pWfSetupAdd]...';


GO



ALTER PROCEDURE [sWf].[pWfSetupAdd]
		@rId [smallint],
		@rWfTypeMasterId [smallint],
		@rWfLevel [smallint],
		@rOrgGroupId [smallint],
		@rWfFunctionalityId [smallint],
        @rAuthorityList sPurchase.ApprovingAuthorityType READONLY
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		BEGIN
			
			IF(@rId = 0 AND not exists(SELECT [AutoId] FROM [NetVidyalaya].[sWf].[tWfSetup] WHERE WfFunctionalityId= @rWfFunctionalityId AND OrgGroupId = @rOrgGroupId))
			BEGIN
				INSERT INTO [sWf].[tWfSetup]
				(
				WfTypeMasterId,
				WfLevel,
				OrgGroupId,
				WfFunctionalityId
				)
				VALUES
				(
				@rWfTypeMasterId,
				@rWfLevel,
				@rOrgGroupId,
				@rWfFunctionalityId
				)
				SET @rId = CAST(SCOPE_IDENTITY() as smallint)

				INSERT INTO sWf.tWfApprovingAuthority
				(
				AuthoritySourceTypeId,
				AuthoritySourceId,
				OrgId,
				WfFunctionalityId
				)
				select 
				AuthoritySourceTypeId,
				AuthoritySourceId,
				OrgId,
				WfFunctionalityId
				from @rAuthorityList

				SELECT @rId
			END
			ELSE
			BEGIN
				UPDATE [sWf].[tWfSetup]
				SET 
					WfTypeMasterId = @rWfTypeMasterId,
					WfLevel = @rWfLevel,
					OrgGroupId = @rOrgGroupId,
					WfFunctionalityId = @rWfFunctionalityId
				WHERE AutoId =@rId

				DELETE FROM sWf.tWfApprovingAuthority
				WHERE WfFunctionalityId = @rWfFunctionalityId

				INSERT INTO sWf.tWfApprovingAuthority
				(
				AuthoritySourceTypeId,
				AuthoritySourceId,
				OrgId,
				WfFunctionalityId
				)
				select 
				AuthoritySourceTypeId,
				AuthoritySourceId,
				OrgId,
				WfFunctionalityId
				from @rAuthorityList

				SELECT @rId
			END
		END
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Altering Procedure [sWf].[pWfSetupGet]...';


GO


ALTER PROCEDURE [sWf].[pWfSetupGet]
	  @rWfFunctionalityId smallint,
	  @rOrgGroupId smallint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select WFS.AutoId,
			   WFS.WfTypeMasterId,
			   WFS.WfLevel,
			   WFS.OrgGroupId,
			   WFS.WfFunctionalityId
		from   [sWf].[tWfSetup] WFS(nolock) 
		where  WFS.WfFunctionalityId = @rWfFunctionalityId AND WFS.OrgGroupId = @rOrgGroupId AND WFS.IsObsolete = 0

		--Declare @wfFunctionalityId smallint
		--select @wfFunctionalityId = WfFunctionalityId
		--from   [sWf].[tWfSetup](nolock) 
		--where  AutoId = @rId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

		select [AutoId]
			  ,[AuthoritySourceTypeId]
			  ,[AuthoritySourceId]
			  ,[OrgId]
			  ,[WfFunctionalityId]
		 from  [sWf].[tWfApprovingAuthority] (nolock) 
		 where WfFunctionalityId = @rWfFunctionalityId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Creating Procedure [sAlert].[pEmployeeBiometricFirstInLastOutListGet]...';


GO

CREATE PROCEDURE [sAlert].[pEmployeeBiometricFirstInLastOutListGet]
	@rEventId int,--127 for firstin 128 LastOut
	@rOrgId int,
	@rTemplate nvarchar(max),
	@rDate dateTime,
	@rMailSubject nvarchar(max)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--set @rDate=cast(@rDate as datetime)

	DECLARE @lDay as nvarchar(3)

	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@rDate) AS varchar(2)), 2)

	DECLARE @lColumnName varchar(10) = '',@lShiftColumntName varchar(10) = ''
	if(@rEventId=127)
	begin
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'
	end
	else if(@rEventId=128)
	begin
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_Out'
	end
	SET @lShiftColumntName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_S'
	DECLARE @Query NVARCHAR(MAX) = ''
	SET @Query = 'SELECT
					EC.MobileNumber AS MobileNo,	
					EC.CompanyEmail AS EmailId,
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[EmployeeName]'',EC.EmployeeName),
					''[PresentTime]'','+@lColumnName+'),
					''[PresentDate]'','''+ISNULL(CONVERT(varchar,@rDate,103),'''')+''')
					 AS Template,
					 '''+@rMailSubject+''' as MailSubject,
					95 AS ReceiverSourceTypeId,
					EC.EmployeeId AS ReceiverSourceId,
					EC.EmployeeName AS Name,
					ISNULL(EC1.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					95 AS SourceTypeId,
					EC.EmployeeId AS SourceId,
					EC.OrgId,
					OM.OrgGroupId,
					EM.Id AS EmployeeId,
					EM.Code,
					OM.Title AS SchoolName,
					OM.DisplayTitle AS OrganizationTitle
		FROM 
				sHrm.tEmployeeMaster EM
				Inner join sHrm.vEmployeeCommonDetail EC ON EM.Id=EC.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC1 ON EC1.EmployeeId = EC.EmployeeId
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = EM.Id AND MT.SourceTypeId = 95 
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
				INNER Join sBiometric.tShiftMasterCloud SM ON SM.ShiftName='+CONVERT(nvarchar(20),@lShiftColumntName)+'
		WHERE
				EM.OrgID = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MT.Attn_dt=cast(rtrim(YEAR('''+CONVERT(nvarchar(20),@rDate)+''') *10000+ Month('''+CONVERT(nvarchar(20),@rDate)+''') *100+ 01) as datetime)
				And '+@lColumnName+' <> ''00:00'' 
				AND EM.StatusId = 7	'
		--print (@Query)
		execute (@Query)	


	
END
GO
PRINT N'Creating Procedure [sAlert].[pOnlineMeetingGet]...';


GO

 
 
CREATE PROCEDURE [sAlert].[pOnlineMeetingGet]
	
		 @rOnlineMeetingId bigint,
	 	 @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,	
			A.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[MeetingType]',DM.Title),
			'[StartDate]',CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103)),
			'[EndDate]',CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103)),
			'[Teacher]',EE.EmployeeName),
			'[Title]',OM.Title)
			AS MsgText,
			'' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 A.OrgId AS OrgId,
			 (SELECT OrgGroupId FROM sSetup.tOrganizationMaster where ID=A.OrgId) AS OrgGroupId,
			 A.AcademicId AS ReceiverSourceId,
			 A.AcademicId AS SourceId,
			 2001 AS SourceTypeId,
			 DM.Title AS MeetingType,
			 CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103) AS StartDate,
			 CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103) AS EndDate,
			 EE.EmployeeName AS Teacher,
			 OM.Title AS Title,
			 A.WhatsAppContactNo
	FROM 
		sEMeeting.tOnlineMeeting OM
		INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId AND DM.DataTypeId = 3
		INNER JOIN sHrm.vExtEmployee EE ON EE.EmployeeId = OM.HostEmployeeId
		INNER JOIN (
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
			    sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
			    OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2003

			UNION ALL

			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
			    sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
			    OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2001

			UNION ALL	
																			 			  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OMS.ScopeSourceId
				 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND  OMS.ScopeSourceTypeId = 2017

			UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2016

			UNION ALL	
																 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2005

			UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2021
			
		) as A ON A.OnlineMeetingId = OM.Id
	WHERE
		OM.Id = @rOnlineMeetingId
END
GO
PRINT N'Creating Procedure [sAlert].[pStudentLeaveApproveRejectGet]...';


GO
CREATE PROCEDURE [sAlert].[pStudentLeaveApproveRejectGet]

	@rAcademicId bigint,
	@rTemplate nvarchar(max),
	@rMailSubject nvarchar(500)='',
	@rLeaveFromDate Date,
	@rLeaveToDate Date,
	@rOrgId int,
	@rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		SA.AcademicId,
		SA.Code,
		SA.Name,
		REPLACE (
		REPLACE (
		REPLACE (
		REPLACE(@rTemplate,'[Name]',SA.Name),
		'[FromDate]',SLR.LeaveFromDate),
		'[ToDate]',SLR.LeaveToDate), 
		'[LeaveReason]',SLR.LeaveReason) AS MsgText,
		@rMailSubject AS Subject,
		2003 AS SourceTypeId,
		SC.StudentId AS SourceId,
		2003 AS ReceiverSourceTypeId,
		SC.StudentId AS ReceiverSourceId,
		ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
		SC.OrgGroupId,
		SC.OrgId
		
	From 
		sStudent.vStudentAcademic SA
		INNER JOIN sStudent.vStudentCommunication SC ON SA.AcademicId = SC.AcademicId AND SC.ClassId=SA.ClassId AND SC.DivisionId=SA.DivisionId
		INNER JOIN sAttendance.tStudentLeaveRequest SLR ON SA.AcademicId = SLR.AcademicId
	WHERE
		(SA.OrgId=@rOrgId)
		AND (SA.BatchId=@rBatchId)
		AND SA.AcademicId = @rAcademicId
		AND SLR.LeaveFromDate = @rLeaveFromDate 
		AND SLR.LeaveToDate = @rLeaveToDate
		AND SC.StatusId = 1
		AND SC.IsBlockAllAlert = 0	

END
GO
PRINT N'Creating Procedure [sAssessment].[pRptGraphicalTeacherEvaluationAnalysis2Get]...';


GO

CREATE PROCEDURE [sAssessment].[pRptGraphicalTeacherEvaluationAnalysis2Get]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int,
	 @rOrgId int=0, 
	 @rGroupByid int=0,
	 @rEmployeeId bigint=0
	 		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	ESGM.Title AS ExamName,
	TSD.EmployeeId,
	EmpM.Code AS EmployeeCode,
	SM.Id AS SubjectId,
	SM.Code AS SubjectCode,
	SM.Title AS SubjectName,
	SM.OrderIndex AS SubjectOrderIndex,
	CS.Id AS ClassSubjectId,
	DM.Id AS DivisionId,
	DM.DisplayTitle AS DivisionName,
	CM.Id AS ClassId,
	CM.DisplayTitle AS ClassName,
	A.Id As AcademicId,
	EM.Id AS ExamId,
	RD.IsPresent,
	RD.Obtain AS SubjectObtain,
	ED.Maximum AS SubjectMaximum,
	CAST(ROUND((ISNULL(RD.Obtain, 0) * 100.0) / ED.Maximum, 2) AS DECIMAL(5,2)) AS SubjectPercentage,
	CASE WHEN @rGroupByid=1 THEN DM.Id
		WHEN @rGroupByid=2 THEN CM.Id
		WHEN @rGroupByid=3 THEN CM.DepartmentId
	    WHEN @rGroupByid=4 THEN OM.Id
		ELSE 0  END  AS HeadId,
	CASE WHEN @rGroupByid=1 THEN ' Division : ' +CM.DisplayTitle+ ' / '+DM.DisplayTitle   
		WHEN @rGroupByid=2 THEN ' Class : ' + CM.DisplayTitle 
		WHEN @rGroupByid=3 THEN 'Department: ' + DP.Title 
		WHEN @rGroupByid=4 THEN  'Organization : '+OM.Title END  AS HeadName,
	CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
		WHEN @rGroupByid=2 THEN CM.OrderIndex
		WHEN @rGroupByid=3 THEN DP.Id
		WHEN @rGroupByid=4 THEN OM.OrderIndex  END AS OrderIndex,
		ED.DisplayOrder 

	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 sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId			
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
		INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId						
		INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON SM.Id = TSD.SubjectId AND DM.Id = TSD.DivisionId
		INNER JOIN sHrm.tEmployeeMaster EmpM ON TSD.EmployeeId = EmpM.Id AND EmpM.StatusId = 7			
			
	WHERE ESGM.Id = @rExamSubGroupId
		AND ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND TSD.EmployeeId=@rEmployeeId
END
GO
PRINT N'Creating Procedure [sAttendance].[pRptYearlyAttendanceGet]...';


GO
CREATE PROCEDURE [sAttendance].[pRptYearlyAttendanceGet]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rDepartmentId int = 0,
	 @rStatus int=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


	DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))

	DECLARE @lOrgId  int
	DECLARE @lSchoolRequiredSignature  nvarchar(500)

	SELECT  @lOrgId=RG.OrgId,
			@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

	DECLARE @Days int
	SELECT @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)

BEGIN
	CREATE TABLE #AttendanceRegistertempTable
	(
		TID int identity(1,1),
		ClassDivisionTitle Nvarchar(500),
		AcademicId bigint,
		AttendanceTypeId int,
		ForYear int,
		ForMonth int,
		ForMonthInWord nvarchar(500),
		ClassId int,
		DivisionId int,
		ClassName nvarchar(500),
		DivisionName nvarchar(500),
		DayPart int,
		ClassOrderIndex int,
		DivisionOrderIndex int,
		StatusId int,
		AttendanceDate date,
		AttendanceTagId int,
		Gender tinyint,
		LeftDate date,
		IsPresent bit
	)

	INSERT INTO #AttendanceRegistertempTable
	(
		ClassDivisionTitle,
		AcademicId,
		AttendanceTypeId,
		ForYear,
		ForMonth,
		ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		DayPart,
		ClassOrderIndex,
		DivisionOrderIndex,
		StatusId,
		AttendanceDate,
		AttendanceTagId,
		Gender,
		LeftDate,
		IsPresent
	)

	SELECT
		ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
		SA.AcademicId,
		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,
		DAY(SR.AttendanceDate) AS DayPart,
		CM.OrderIndex AS ClassOrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.StatusId,
		SR.AttendanceDate AS AttendanceDate,
		SR.AttendanceTagId,
		SO.GenderId,
		A.LeftDate,
		SR.IsPresent

    FROM
		sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
		INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
		--LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		--LEFT JOIN  sStudent.tStudentFamily SF ON Sf.StudentId=Sa.StudentID
		--LEFT JOIN sCommon.tReligionMaster RE On RE.Id=SO.ReligionId
		--LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId

	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.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	    AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	    AND ((SA.StatusId=@rStatus)OR (@rStatus=0))
	    --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
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		PivotTable.AcademicId,
		ClassDivisionTitle,
		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,
		(ISNULL(TotalPresent,0) + ISNULL(TC.TCount,0)) AS TotalPresent,
		sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth,
		Gender

	FROM
	(
		SELECT
			ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
			AcademicId,
			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,
			ClassOrderIndex,
			DivisionOrderIndex,
			Gender,
			LeftDate
		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 ((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))
		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 ((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))
		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))
		GROUP BY	A.Id
    ) AA ON AA.AcademicId = PivotTable.AcademicId



SELECT * FROM #TempDaysTempTable

DROP TABLE #AttendanceRegistertempTable
DROP TABLE #TempDaysTempTable



	--SELECT
	--		'' AS Builder1,
	--		'' AS Builder2,
	--		Convert(bigint,0) AS AcademicId,
	--		'' AS ClassDivisionTitle,
	--		0 as AttendanceTypeId,
	--		0 as ForYear,
	--		0 as ForMonth,
	--		0 as ClassId,
	--		'' as ClassName,
	--		0 as DivisionId,
	--		'' as DivisionName,
	--		'' as ForMonthInWord,
	--		0 AS PresentCount,
	--		0 AS AbsentUpto,
	--		0 AS AttendanceCount,
	--	    0 As AbsentCount,
	--	    0 As PresentUpto,
	--	    0 as ClassOrderIndex,
	--	    0 as DivisionOrderIndex,
	--		0 AS TotalPresent,
	--		0 AS DaysInMonth,
	--		0 as Gender,
	--		Convert(date,'') AS LeftDate

END
GO

PRINT N'Creating Procedure [sBiometric].[pShiftMasterDelete]...';


GO
 
CREATE PROCEDURE [sBiometric].[pShiftMasterDelete]
	@rShiftcode int,
	@rOrgGroupId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
	 
  		IF EXISTS( SELECT 1 FROM sHrm.tEmployeeMaster WHERE ShiftId = @rShiftcode)	
		BEGIN
			SELECT 101 AS RESULT
		END	
		ELSE IF EXISTS( SELECT 1 FROM sStudent.tStudentMaster WHERE ShiftId = @rShiftcode)	
		BEGIN
			SELECT -102 AS RESULT
		END	
		ELSE IF EXISTS( SELECT 1 FROM  sBiometric.tShiftAllocationCloud WHERE ShiftCode = @rShiftcode)	
		BEGIN
			SELECT -103 AS RESULT
		END 
		ELSE
		BEGIN
			DELETE FROM sBiometric.tShiftMasterCloud WHERE ShiftCode = @rShiftcode and OrgGroupId = @rOrgGroupId
			SELECT 1 AS RESULT
		END


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


GO

CREATE PROCEDURE [sBiometric].[pTimeSheetListStudentGet]
	@rOrgId int,
	@rFromDate DateTime,  
    @rToDate DateTime, 
	@rStudentId bigint,
	@rClassId int=0,
	@rDivisionId int=0,
	@rStatusId int=0,
	@rBatchId  int
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   

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

	
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId = 2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E,D05_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	--IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	--BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
		 AND (((Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) 
		OR ((Month(@rToDate) <> 2 or (((YEAR(@rToDate) % 4 = 0 AND YEAR(@rToDate) % 100 <> 0) OR YEAR(@rToDate) % 400 = 0 And Month(@rToDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime))) 
		AND ( SourceTypeId =2003)
	--END
	
	--IF Month(@rFromDate) <> 2
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ((Month(@rFromDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) Or (Month(@rToDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2003)
	--END
	
	--IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ((Month(@rFromDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) OR (Month(@rToDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2003)
	--END

	Update TM set PresentStatus = CASE When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='PW')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
		 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW' 
		 --When ((TM.PresentStatus='XX')AND (Cast(TM.Attn_Date as date)<GETDATE()) And (cast(AD.AdmissionDate as date)<= Cast(TM.Attn_Date as date) OR ISNULL(AD.AdmissionDate,'')='')AND (AD.LeftDate>= Cast(TM.Attn_Date as date) OR ISNULL(AD.LeftDate,'')='') AND (TM.FirstIn ='00:00'))  then 'A'
		 ELSE TM.PresentStatus END
		From #TempMonthTrans TM
		INNER JOIN sStudent.vStudentAcademic SA  ON SA.StudentId = TM.EmployeeId 
		--INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId

--select * from #TempMonthTrans 
	Select 
		SA.AcademicId AS AcademicId,
		SA.StudentId AS StudentId,
		TM.Attn_Date AS  Attn_Date,
		TM.FirstIn,
		TM.LastOut,
		TM.OverTime,
		TM.LateBy,
		TM.Duration,
		TM.EarlyBy,
		TM.ShiftName,
		TM.PresentStatus as PresentStatus,
		SA.Code AS StudentCode,
		SA.Name AS StudentName,
		ISNULL(SA.RollNo,0) as RollNo,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='A') AS TotalAbsentDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='W') AS TotalWeekOffs,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='H') AS TotalHolidays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND (PresentStatus='P' OR PresentStatus='PW')) AS TotalPresentDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='HD') AS TotalHalfDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='LH') AS TotalLessHours,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='E') AS TotalErrorCase,
		 OM.DisplayTitle AS Organization,
		CM.DisplayTitle AS ClassName,
		CM.Id AS ClassId,
		DM.DisplayTitle AS DivisionName,
		DM.Id AS DivisionId,
		Dept.DisplayTitle AS Department,
		Dept.Id AS DepartmentId,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		Dept.OrderIndex AS OrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.OrgId AS OrgId--,
		--DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays
				
		 From #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND SourceTypeId = 2003 
	 INNER JOIN sStudent.vStudentAcademic SA  ON SA.StudentId = MT.EmployeeId AND MT.SourceTypeId=2003 
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
	INNER JOIN sSetup.tDivisionMaster DM  ON  SA.DivisionId=DM.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	--INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
	
	WHERE 
			SA.OrgId=@rOrgId 
			AND	((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (SA.StudentId=@rStudentId OR @rStudentId=0)
			AND ( (SA.StatusId =  @rStatusId) OR @rStatusId=0)
			AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rToDate)
			AND SA.BatchId = @rBatchId
			 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			 
	ORDER BY SA.RollNo

	DROP Table #TempMonthTrans	
END
GO
PRINT N'Creating Procedure [sCommunication].[pCircularConsentResultAdd]...';


GO


CREATE PROCEDURE [sCommunication].[pCircularConsentResultAdd]
	 
		@rSourceId bigint,
        @rCircularConsentId bigint,
		@rCircularConsentAns nvarchar(max)
	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	INSERT INTO [sCommunication].[tCircularConsentResult]
		(
			SourceId,
			CircularConsentId,
			CircularConsentAns
		)
	VALUES
		(
			@rSourceId,
			@rCircularConsentId,
			@rCircularConsentAns
		)

	 
	 SELECT 1 AS Result

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


GO


CREATE PROCEDURE [sCommunication].[pCircularConsentResultGet]
	 	 
		 @rCircularId bigint,
	 	 @rOrgId int
	 	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
 
			A.Code,
			A.Name,
			A.CircularConsentAns,
			A.ClassDept
	From 
			sCommunication.tCircular CR
			
			INNER JOIN (
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
			WHERE 
				SC.StatusId = 1 
				AND CS.SourceTypeId = 2003

			UNION ALL

			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.AcademicId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
			WHERE 
				SC.StatusId = 1 
				AND CS.SourceTypeId = 2001
			
			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				vEC.DepartmentName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.EmployeeId = CS.SourceId 
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = vEC.EmployeeId
			WHERE 
				vEC.StatusId = 7 
				AND CS.SourceTypeId = 95
				
			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.DepartmentId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
				 
			WHERE 
				SC.StatusId = 1 
				AND  CS.SourceTypeId = 2017 AND CS.AssigneeToId = 2
				

			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				vEC.DepartmentName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.DepartmentId = CS.SourceId 
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = vEC.EmployeeId
			WHERE 
				vEC.StatusId = 7 
				AND CS.SourceTypeId = 2017 AND CS.AssigneeToId = 3 

			UNION ALL	
		
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.ClassId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
				 
			WHERE 
				SC.StatusId = 1 
				AND CS.SourceTypeId = 2016 AND CS.AssigneeToId = 2 
				

			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.DivisionId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
				 
			WHERE 
				SC.StatusId = 1 
				AND  CS.SourceTypeId = 2005 AND CS.AssigneeToId = 2 
				
			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.OrgId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
				 
			WHERE 
				SC.StatusId = 1 
				AND CS.SourceTypeId = 2021 AND CS.AssigneeToId = 2 

			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				vEC.DepartmentName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.OrgID = CS.SourceId 
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = vEC.EmployeeId
			WHERE 
				vEC.StatusId = 7 
				AND CS.SourceTypeId = 2021 AND CS.AssigneeToId = 3 
			
		) as A ON A.CircularId = CR.Id 
	WHERE
			A.OrgId = @rOrgId AND A.CircularId = @rCircularId
END
GO
PRINT N'Creating Procedure [sCommunication].[pDailyThoughtAssignSearchGet]...';


GO
CREATE PROCEDURE [sCommunication].[pDailyThoughtAssignSearchGet]
	 @rOrgId int,
	 @rDay smallint,
	 @rMonth smallint,
	 @rDivisionId int = 0,
	 @rClassId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	SELECT
		DTA.DailyThoughtId AS Id,
		STUFF ((SELECT ','+ CAST(Number AS nvarchar(20))
		FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
		FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Number,
		STUFF ((SELECT ', '+ Title
		FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
		FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Title,
		STUFF ((SELECT ', '+ Remark
		FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
		FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Remark 
	FROM 
		sCommunication.tDailyThoughtAssign DTA 
	WHERE DTA.OrgId = @rOrgId 
		AND DTA.Day = @rDay AND DTA.Month = @rMonth 
		AND (((DTA.SourceTypeId = 2021 AND DTA.SourceId = @rOrgId) OR (DTA.SourceTypeId IS NULL AND DTA.SourceId IS NULL)) OR
			   ((DTA.SourceTypeId = 2005 AND DTA.SourceId = @rDivisionId)) 
			OR ((DTA.SourceTypeId = 2016 AND DTA.SourceId = @rClassId)))
	ORDER BY DTA.AutoId DESC
END
GO
PRINT N'Creating Procedure [sEMeeting].[pAttachmentLogAdd]...';


GO

CREATE PROCEDURE [sEMeeting].[pAttachmentLogAdd]
		@rMessageId nvarchar(max),
		@rAttachment nvarchar(max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY	
			INSERT INTO sAlert.tAlertAttachmentLog VALUES (@rMessageId, @rAttachment)
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pBatchLockGet]...';


GO

CREATE PROC [sEMeeting].[pBatchLockGet]
	@rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY

	Select ISNULL(IsLock,0) as IsLock FROM sSetup.tBatchMaster WHERE Id = @rBatchId

	END TRY

	BEGIN CATCH
	SELECT -1 as Result
	END CATCH

END
GO
PRINT N'Creating Procedure [sEMeeting].[pCreateSMSStatus]...';


GO

CREATE PROCEDURE [sEMeeting].[pCreateSMSStatus]
		@rResultMessage nvarchar(max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			Insert Into sAlert.tSMSStatus VALUES (CONVERT(DateTime,GetUtcDate(),103), @rResultMessage)
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pEmployeeMasterIdGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pEmployeeMasterIdGet]
		@rMobileNotificationCode nvarchar(max),
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT Id FROM sHrm.tEmployeeMaster WHERE Code = @rMobileNotificationCode AND OrgId= @rOrgId AND  ISNULL(IsOtherUser,0) = 0 
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pEventSMSTemplateIdGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pEventSMSTemplateIdGet]
		@rOrgId int,
		@rEventId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			Select SMSTemplateID FROM sAlert.tEventTemplate WHERE EventId = @rOrgId AND OrgId=@rOrgId AND AlertModeId = 2
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pEventTemplateGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pEventTemplateGet]
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT EventId,Template FROM sAlert.tEventTemplate WHERE IsAutoSend = 1 AND OrgId =@rOrgId AND EventId = 93 AND AlertModeId in (3)
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pMeetingAccountNameGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pMeetingAccountNameGet]
		@rEmployeeId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
	SELECT OMA.Id,
	OMA.AccountName as Title
	FROM sAcademic.tOnlineMeetingAccount OMA 
	WHERE EmployeeId = @rEmployeeId 
	AND ISNULL(OMA.IsObsolete,0) = 0
	END TRY
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pMeetingTypeMasterDelete]...';


GO
 
CREATE PROCEDURE [sEMeeting].[pMeetingTypeMasterDelete]
	 @rId smallint

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	IF EXISTS (SELECT 1 from sEMeeting.tMeetingTypeMaster where AutoId = @rId AND IsObsolete = 0)
	BEGIN 
	Update sEMeeting.tMeetingTypeMaster
	SET 
		IsObsolete = 1
	WHERE AutoId = @rId
	SELECT 1 As Result
	END
END TRY
BEGIN CATCH 
		SELECT -1 AS Result
END CATCH
END
GO
PRINT N'Creating Procedure [sEMeeting].[pMeetingTypeMasterDetailGet]...';


GO
 
CREATE PROCEDURE [sEMeeting].[pMeetingTypeMasterDetailGet]
	 @rId smallint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	If(@rId = 0)
	BEGIN 
		SELECT AutoId, Title, Code, OrderIndex, Description
			from [sEMeeting].[tMeetingTypeMaster] where IsObsolete = 0
	END
	ELSE
	BEGIN
		SELECT AutoId, Title, Code, OrderIndex, Description
			from [sEMeeting].[tMeetingTypeMaster] where AutoId = @rId AND IsObsolete = 0
	END
END TRY
BEGIN CATCH 
		SELECT -1 AS Result
END CATCH
END
GO
PRINT N'Creating Procedure [sEMeeting].[pMobileNotitficationTitleGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pMobileNotitficationTitleGet]
		@rEventId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY	
			SELECT Title FROM sAlert.tEventMaster WHERE Id= @rEventId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pNotitficationLogIdGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pNotitficationLogIdGet]
		@rFromId bigint,
		@rToId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY	
			SELECT Id AS NotificationId FROM sAlert.tNotificationLog WHERE (Id>=@rFromId) AND (Id<=@rToId)
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingAccountDetailsGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAccountDetailsGet]
	@rMeetingAccountId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT OAuthAccountId,OAuthClientId,OAuthClientSecret,AccountEmailId,JWTToken FROM sAcademic.tOnlineMeetingAccount WHERE Id = @rMeetingAccountId AND ISNULL(IsObsolete,0) = 0
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingAccounts]...';


GO

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAccounts]
	@rOnlineMeetingAccountId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT STUFF((SELECT ','+ CONVERT(varchar,OM.Id) FROM sEMeeting.tOnlineMeeting OM WHERE MeetingAccountId =  @rOnlineMeetingAccountId AND IsCompleted = 0								FOR XML PATH('')), 1, 1, '') AS Ids
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingAssigneeGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAssigneeGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT Id,
			Title 
			FROM sCommon.tAssigneeMaster
			WHERE IsObsolete=0 ORDER BY Id
		END TRY
		BEGIN CATCH 
		SELECT -1 AS Result
		END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingAttendanceAdd]...';


GO


CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAttendanceAdd]
	 @rOnlineMeetingId bigint ,
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rAttendanceTypeId int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	 
	 IF(@rAttendanceTypeId= 1) 
	   BEGIN
	   IF NOT EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeetingAttendance WHERE OnlineMeetingId = @rOnlineMeetingId AND ParticipantSourceId = @rSourceId AND ParticipantSourceTypeId = @rSourceTypeId)
			BEGIN
			INSERT  INTO sEMeeting.tOnlineMeetingAttendance
			(OnlineMeetingId,ParticipantSourceTypeId, ParticipantSourceId, IsPresent ,FirstInDateTime, IsLoggedIn)
			VALUES 
			(@rOnlineMeetingId, @rSourceTypeId, @rSourceId,1,GetDate(), 1)
			END
		SELECT 1 AS Result	
		END
		
		ELSE IF (@rAttendanceTypeId= 2)
		BEGIN
		IF EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeetingAttendance WHERE OnlineMeetingId = @rOnlineMeetingId AND ParticipantSourceId = @rSourceId AND ParticipantSourceTypeId = @rSourceTypeId)
			BEGIN
			UPDATE sEMeeting.tOnlineMeetingAttendance 
			SET LastOutDateTime = GetDate(),
			IsLoggedIn = 0
			Where ParticipantSourceId= @rSourceId AND OnlineMeetingId= @rOnlineMeetingId And ParticipantSourceTypeId = @rSourceTypeId
			SELECT 11 AS Result
			END
			
		ELSE 
		SELECT -1 AS Result
	
END
END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingAttendanceGet]...';


GO


CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAttendanceGet]
	@rOnlineMeetingId bigint
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	CREATE TABLE #ScopeSourceTypeId
	(
		Id int IDENTITY,
		ScopeSourceTypeId bigint
	)
	CREATE TABLE #StudentData
	(
	Class nvarchar(200),
	Code nvarchar(200),
	RollNo bigint,
	StudentName nvarchar(200),
	IsPresent nvarchar(100),
	ClassID bigint,
	DivisionId bigint,
	AcademicId bigint,
	IsLoggedIn nvarchar(100),
	FirstInDateTime datetime,
	LastOutDateTime datetime,
	IsPresentAbsent nvarchar(100)
	)

	INSERT INTO #ScopeSourceTypeId
	Select Distinct  ScopeSourceTypeId from [sEMeeting].[tOnlineMeetingScope] Where OnlineMeetingId=@rOnlineMeetingId

DECLARE @lCountScopeSourceTypeId int,@lScopeSourceTypeId int,@lId int

SELECT @lCountScopeSourceTypeId=COUNT(ScopeSourceTypeId) FROM #ScopeSourceTypeId
	SELECT Top 1 @lId=Id FROM #ScopeSourceTypeId

	WHILE @lId <= @lCountScopeSourceTypeId
			BEGIN
			SELECT @lScopeSourceTypeId=ScopeSourceTypeId FROM #ScopeSourceTypeId WHERE Id=@lId
	--AcademicId
	IF(@lScopeSourceTypeId=2001)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT  OMA.FirstInDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.AcademicId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--ClassId
	ELSE IF(@lScopeSourceTypeId=2016)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OMA.FirstInDateTime  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.ClassId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY 
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--DeparmentId
	ELSE IF(@lScopeSourceTypeId=2017)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OMA.FirstInDateTime  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.DepartmentId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY 
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--OrgId
	ELSE IF(@lScopeSourceTypeId=2021)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OMA.FirstInDateTime  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.OrgId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY 
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--Division
	ELSE IF(@lScopeSourceTypeId=2005)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OMA.FirstInDateTime  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.DivisionId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId 
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY 
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END

	SET @lId=@lId+1
	END
	Select * from #StudentData
	DROP TABLE #ScopeSourceTypeId
	DROP TABLE #StudentData
				
END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingClassGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingClassGet]
	@rDepartmentId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		SELECT Id, DisplayTitle as Title FROM sSetup.tClassMaster WHERE IsObsolete = 0 AND DepartmentId = @rDepartmentId
	END TRY

	BEGIN CATCH
	 SELECT -1 as Result
	END CATCH

END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingDelete]...';


GO
 
 CREATE PROCEDURE [sEMeeting].[pOnlineMeetingDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete from sEMeeting.tOnlineMeetingResource where OnlineMeetingId=@rId
			Delete from sEMeeting.tOnlineMeetingReference where OnlineMeetingId=@rId
			Delete from sEMeeting.tOnlineMeetingAttendance where OnlineMeetingId=@rId
			Delete from sEMeeting.tOnlineMeetingScope where OnlineMeetingId=@rId
			Delete from sEMeeting.tOnlineMeetingSettings Where OnlineMeetingId = @rId
			Delete from sEMeeting.tOnlineMeeting 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 Procedure [sEMeeting].[pOnlineMeetingDepartmentGet]...';


GO


CREATE PROCEDURE [sEMeeting].[pOnlineMeetingDepartmentGet]
		@rOrgId int,
		@rUserId bigint 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT 
		DM.Id, 
		DM.DisplayTitle AS Title 
		FROM sSetup.tDepartmentMaster DM 
		INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id 
		AND U.SourceTypeId=2017
        WHERE IsObsolete = 0 
		AND OrgId = @rOrgId  
		AND UserId = @rUserId
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingDivisionGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingDivisionGet]
	 
	 @rClassId int,
	 @rUserSourceId bigint,
	 @rOrgId int,
	 @rUserId bigint,
	 @rBatchId int,
	 @rAttendanceEntryBasedOn nvarchar
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	BEGIN TRY
        if (@rAttendanceEntryBasedOn = 'Class Teacher')
			BEGIN
				SELECT  
					DM.Id ,  
					DM.DisplayTitle AS Title  
					FROM sSetup.tDivisionMaster DM  
					WHERE  InchargeemployeeID= @rUserSourceId 
					AND  OrgId= @rOrgId  
					AND classId = @rclassId AND IsObsolete = 0
			END	 
        else if (@rAttendanceEntryBasedOn = 'Class Teacher Batch')
			BEGIN
				SELECT  
					DM.Id,  
					DM.DisplayTitle AS Title 
					FROM sSetup.tDivisionMaster DM 
					INNER JOIN sSetup.tDivisionInchargeEmployee DIE 
					ON DIE.DivisionId = DM.Id 
					WHERE  DIE.EmployeeId= @rUserSourceId
					AND DM.OrgId= @rOrgId 
					AND DM.ClassId= @rClassId 
					AND DIE.BatchId= @rBatchId  
					AND DM.IsObsolete = 0
			END
		else if (@rAttendanceEntryBasedOn = 'Academic Setup')
				BEGIN
					SELECT 
						DivisionId AS Id, 
						DivisionTitle AS Title 
						FROM sAcademic.vTeacherSubjectDivision 
						WHERE EmployeeId= @rUserSourceId 
						AND ClassId= @rClassId 
						AND OrgId= @rOrgId 
						AND DMIsObsolete = 0
				END
		else if (@rAttendanceEntryBasedOn = 'User Access')
				BEGIN
					Select 
						DM.Id,
						DM.Title 
						from sSetup.tDivisionMaster DM  
						INNER JOIN sSecurity.tUserAccess U 
						ON U.SourceId = DM.Id
                        Where DM.OrgId = @rOrgId 
						AND U.SourceTypeId=2005 
						AND U.UserId= @rUserId 
						AND ClassId= @rClassId 
						AND DM.IsObsolete = 0
				END
		else if (@rAttendanceEntryBasedOn = '')
					BEGIN
						SELECT 
							Id,
							Title 
							FROM sSetup.tDivisionMaster 
							WHERE IsObsolete = 0  
							AND ClassId= @rClassId 
							ORDER BY OrderIndex
					END
	END TRY

	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingOrganizationGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingOrganizationGet]
		@rOrgGroupId int,
		@rUserId bigint 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT 
		UO.Id, 
		UO.DisplayTitle AS Title 
		FROM sSetup.vUserOrganization UO
        WHERE IsObsolete = 0 
		AND OrgGroupId = @rOrgGroupId  
		AND UserId = @rUserId
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingProviderGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingProviderGet]
	@rMeetingAccountId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT MeetingProviderId FROM sAcademic.tOnlineMeetingAccount WHERE Id = @rMeetingAccountId AND ISNULL(IsObsolete,0) = 0
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingReferenceDelete]...';


GO
 
CREATE PROCEDURE [sEMeeting].[pOnlineMeetingReferenceDelete]

        @rOnlineMeetingId bigint,
		@rReferencePath nvarchar(Max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF NOT EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeetingReference WHERE OnlineMeetingId = @rOnlineMeetingId AND ReferencePath = @rReferencePath)
	BEGIN 
		SELECT -1 AS Result
	END
	ELSE
	BEGIN
		DELETE FROM sEMeeting.tOnlineMeetingReference
		WHERE OnlineMeetingId = @rOnlineMeetingId 
		AND ReferencePath = @rReferencePath
		SELECT 1 AS Result
	END
END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingResourceAdd]...';


GO

 
 
CREATE PROCEDURE [sEMeeting].[pOnlineMeetingResourceAdd]
	 
	@rOnlineMeetingId bigint,
	@rResourceTypeId smallint,
	@rResourcePath nvarchar(max),	
	@rIsObsolete bit = 0,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

	IF NOT EXISTS (SELECT 1 FROM [sEMeeting].[tOnlineMeetingResource] WHERE OnlineMeetingId = @rOnlineMeetingId AND ResourcePath = @rResourcePath)
	BEGIN		
	INSERT INTO [sEMeeting].[tOnlineMeetingResource]	
		(
		OnlineMeetingId,
		ResourceTypeId,
		ResourcePath,
		IsObsolete,
		CreatedUserId,
		CreatedDateTime
		)
	VALUES
		(
		@rOnlineMeetingId,
		@rResourceTypeId,
		@rResourcePath,
		@rIsObsolete,
		@rCreatedUserId,
		GetUtcDate()
		)
	END
	COMMIT TRANSACTION
		SELECT 1 AS Result		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingStatusTypeGet]...';


GO

 
CREATE PROCEDURE [sEMeeting].[pOnlineMeetingStatusTypeGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
	SELECT 
	SM.Id,
	SM.Title 
	FROM sCommon.tStatusMaster SM 
	WHERE StatusTypeId = 113 ORDER BY Id
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingStudentGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingStudentGet]
	@rDivisionId int,
	@rOrgId int,
	@rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY

	BEGIN
		SELECT AcademicId as Id,(Code+' - '+CONVERT(NVARCHAR(10),RollNo)+' - '+Name) AS Title from sStudent.vStudentAcademic WHERE StatusId=1 AND DivisionId = @rDivisionId AND				OrgId = @rOrgId AND BatchId = @rBatchId ORDER BY RollNo 
	END 

	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating Procedure [sEMeeting].[pOrgGroupIdGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pOrgGroupIdGet]
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pSMSTemplateIdGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pSMSTemplateIdGet]
		@rOrgId int,
		@rCustomEventId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT SMSTemplateID FROM sAlert.tCustomTemplateMaster WHERE Id = @rCustomEventId AND OrgId = @rOrgId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pUpdateMeetingDetails]...';


GO

CREATE PROC [sEMeeting].[pUpdateMeetingDetails]
	@rId bigint,
	@rType nvarchar(20)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
 
	IF EXISTS (SELECT 1 from [sEMeeting].[tOnlineMeeting] where Id = @rId AND @rType IN ('Join', 'Start Again', 'Complete'))
	BEGIN
	IF (@rType = 'Join')
		UPDATE [sEMeeting].[tOnlineMeeting] SET IsMeetingStarted=1, StartDateTime = GetUtcDate() WHERE Id= @rId

	ELSE IF (@rType = 'Start Again')
		UPDATE [sEMeeting].[tOnlineMeeting] SET IsCompleted=0,IsMeetingStarted=1 WHERE Id= @rId	

	ELSE IF (@rType = 'Complete')
		UPDATE [sEMeeting].[tOnlineMeeting] SET IsCompleted=1,IsMeetingStarted=0,EndDateTime = GetUtcDate() WHERE Id= @rId

	SELECT 1 as Result
	END 
	ELSE
	BEGIN
		SELECT -101 as Result
	END
	END TRY

	BEGIN CATCH
	SELECT -1 as Result
	END CATCH

END
GO
PRINT N'Creating Procedure [sEMeeting].[pUpdateOnlineMeetingAccountToken]...';


GO

CREATE PROCEDURE [sEMeeting].[pUpdateOnlineMeetingAccountToken]
	@rAccessToken nvarchar(max),
	@rOnlineMeetingAccountId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			UPDATE sAcademic.tOnlineMeetingAccount SET JWTToken = @rAccessToken Where Id = @rOnlineMeetingAccountId AND MeetingProviderId = 1
			SELECT 11 as Result
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pUpdateOnlineMeetingSettingsToken]...';


GO

CREATE PROCEDURE [sEMeeting].[pUpdateOnlineMeetingSettingsToken]
	@rAccessToken nvarchar(max),
	@rOnlineMeetingIds nvarchar(max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			UPDATE sEMeeting.tOnlineMeetingSettings SET JWTToken = @rAccessToken WHERE OnlineMeetingId IN (@rOnlineMeetingIds)
			SELECT 11 as Result
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pValidateOnlineMeetingAccount]...';


GO


CREATE PROCEDURE [sEMeeting].[pValidateOnlineMeetingAccount]
@rId bigint = 0,
@rStartDate nvarchar(50),
@rStartTime nvarchar(50),
@rEndDate nvarchar(50),
@rEndTime nvarchar(50),
@rMeetingAccountId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
		if(@rId = 0)
		BEGIN
			SELECT 1 
			FROM sEMeeting.tOnlineMeeting 
			WHERE (((StartDate <= @rStartDate) 
			AND (EndDate >= @rEndDate)) 
			OR ((StartDate >= @rStartDate) 
			AND (EndDate <= @rEndDate)))
            AND (((StartTime <= @rStartTime) 
			AND (EndTime >= @rEndTime)) 
			OR ((StartTime <=  @rStartTime) 
			AND (EndTime >= @rEndTime))) 
			AND MeetingAccountId = @rMeetingAccountId
		END
		ELSE
		BEGIN
			SELECT 1 
			FROM sEMeeting.tOnlineMeeting OM
			WHERE (((StartDate <= @rStartDate) 
			AND (EndDate >= @rEndDate)) 
			OR ((StartDate >= @rStartDate) 
			AND (EndDate <= @rEndDate)))
            AND (((StartTime <= @rStartTime) 
			AND (EndTime >= @rEndTime)) 
			OR ((StartTime <= @rEndTime) 
			AND (EndTime >= @rStartTime))) 
			AND @rId = OM.Id
			AND MeetingAccountId = @rMeetingAccountId
		END
		END TRY
		BEGIN CATCH
		SELECT -101 AS Result
		END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pValidateOnlineMeetingTeacher]...';


GO


CREATE PROCEDURE [sEMeeting].[pValidateOnlineMeetingTeacher]
@rId bigint = 0,
@rStartDate nvarchar(50),
@rStartTime nvarchar(50),
@rEndDate nvarchar(50),
@rEndTime nvarchar(50),
@rMeetingAccountId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
		BEGIN
			SELECT 1 
			FROM sEMeeting.tOnlineMeeting OM
			WHERE  HostEmployeeId = @rId
			AND (((StartDate <= @rStartDate) 
			AND (EndDate >= @rStartDate)) 
			OR ((StartDate >= @rEndDate) 
			AND (EndDate <= @rEndDate)))
            AND (((StartTime <= @rStartTime) 
			AND (EndTime >= @rEndTime)) 
			OR ((StartTime <= @rEndTime) 
			AND (EndTime >= @rStartTime)))
		END
		END TRY
		BEGIN CATCH
		SELECT -101 AS Result
		END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pWhatsAppTemplateGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pWhatsAppTemplateGet]
		@rEventId int,
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY	
			SELECT Template,WhatsAppTemplate,WhatsAppTemplateLanguage FROM sAlert.tEventTemplate WHERE EventId = @rEventId AND OrgId = @rOrgId AND AlertModeId = 4
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Creating Procedure [sPurchase].[GetPagedData]...';


GO
CREATE PROCEDURE sPurchase.GetPagedData
(
    @PageNumber BIGINT,
    @PageSize BIGINT
)
AS
BEGIN
        DECLARE @StartIndex BIGINT;
    DECLARE @EndIndex BIGINT;
    DECLARE @TotalRecords BIGINT;

    -- Calculate the offset to skip the appropriate number of rows
	  SET @StartIndex = (@PageNumber - 1) * @PageSize;
    SET @EndIndex = @StartIndex + @PageSize;

    -- Get the total number of records
    SELECT @TotalRecords = COUNT(*) FROM sPurchase.tGoodsReceivedNote;

    -- Retrieve the paged data
    SELECT *
    FROM sPurchase.tGoodsReceivedNote
    WHERE ID >= @StartIndex AND ID < @EndIndex
    ORDER BY ID; 

    -- Return the total number of records for client-side pagination
    SELECT @TotalRecords AS TotalRecords;
END
GO
PRINT N'Creating Procedure [sPurchase].[pDocumentManagementAdminGet]...';


GO



CREATE PROCEDURE [sPurchase].[pDocumentManagementAdminGet]
	  @rUserId bigint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  DM.AutoId,
				DM.FileName,
				DM.Size,
				DM.DocumentUrl,
				STM.Title as SourceName,
				DM.OrgGroupId,
				DM.SourceId,
				DM.SourceTypeId,
				DM.UserId,
				U.DisplayTitle as UserName
		from   [sPurchase].[tDocumentManagement] DM(nolock) 
			   LEFT JOIN sCommon.tSourceTypeMaster STM on DM.SourceTypeId = STM.Id
			   Left join sSecurity.tUser U on DM.UserId = U.Id
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pDocumentManagementGet]...';


GO



CREATE PROCEDURE [sPurchase].[pDocumentManagementGet]
	  @rUserId bigint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  DM.AutoId,
				DM.FileName,
				DM.Size,
				DM.DocumentUrl,
				STM.Title as SourceName,
				DM.OrgGroupId,
				DM.SourceId,
				DM.SourceTypeId,
				DM.UserId
		from   [sPurchase].[tDocumentManagement] DM(nolock) 
			   LEFT JOIN sCommon.tSourceTypeMaster STM on DM.SourceTypeId = STM.Id
		where  UserId = @rUserId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pInvoiceGenerateDelete]...';


GO




CREATE PROCEDURE [sPurchase].[pInvoiceGenerateDelete]
		@rId bigint,
		@rStatusId smallint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		If(@rId > 0)
		Begin
			Update sPurchase.tInvoiceGenerate
			set 
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			if exists(select Id From sPurchase.tInvoiceGenerateDetail where InvoiceGenerateId = @rId)
			Begin
				delete from sPurchase.tInvoiceGenerateDetail
				where InvoiceGenerateId = @rId
			End
			select 1
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseScreenGet]...';


GO

CREATE PROCEDURE [sPurchase].[pPurchaseScreenGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
	SELECT	
		S.Id			AS ScreenId,
		S.Title		AS ScreenTitle,
		S.TaskId		AS TaskId,	
		S.Page		As PageUrl,
		S.IsObsolete	AS ScreenIsObsolete,	
		S.Title,		
		S.Page,
		SG.Id AS ScreenGroupId,
		ISNULL(SG.Title,'') AS ScreenGroupName
		
	FROM 
		sSecurity.tScreen S
	LEFT JOIN sSecurity.tScreenGroupMaster SG ON SG.Id=S.ScreenGroupId
	WHERE 
		S.IsObsolete = 0 and S.ScreenGroupID=254
end
GO
PRINT N'Creating Procedure [sTimetable].[pDeleteTimeTable]...';


GO
CREATE PROCEDURE [sTimetable].[pDeleteTimeTable]

	  @rBatchId int,
	  @rTimeTableId int,
	  @rSelect nvarchar(100),
	  @rTimeTableSchemaId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rSelect='Proxy Setting')
	BEGIN
		DELETE FROM sTimetable.tProxySetting WHERE TimeTableSchemaId=@rTimeTableSchemaId
		--AND BatchId=@rBatchId AND TimeTableId=@rTimeTableId
	END

	ELSE IF(@rSelect='Assign Time Table Time')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tProxySetting WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 101 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId=@rTimeTableSchemaId
	END

	ELSE IF(@rSelect='Time Table')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 102 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTimeTable WHERE TimeTableSchemaId=@rTimeTableSchemaId
	END

	ELSE IF (@rSelect='Teacher Work Load')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tTimeTable WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 103 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId
	END

	ELSE IF (@rSelect='Division Work Load')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 104 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId
	END

	ELSE IF (@rSelect='Time Setup')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 105 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTimeSetup WHERE TimeTableSchemaId=@rTimeTableSchemaId
	END
END



--sTimetable.tTimeSetup where TimeTableSchemaId=991100008 order by classid
--sTimetable.tDivisionWorkLoad where TimeTableSchemaId=991100008
--sTimetable.tTeacherWorkLoad where TimeTableSchemaId=991100008
--sTimetable.tTimeTable where TimeTableSchemaId=991100008
--sTimetable.tTimeTableTime where TimeTableSchemaId=991100008
--sTimetable.tProxySetting where TimeTableSchemaId=991100008
GO
PRINT N'Creating Procedure [sTimetable].[pTimeTableTimeListGet]...';


GO
CREATE PROCEDURE [sTimetable].[pTimeTableTimeListGet]
	   
	  @rBatchId int,
	  --@rEmployeeId bigint,
	  @rDayIds nvarchar(100)='',
	  @rLectureNo smallint,
	  @rTimeTableSchemaId int,
	  @rOrgId int=0,
	  @rDivisionId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN    
	SELECT 	 
	--TT.Id AS TimeTableID,
	TTT.AutoId AS AutoId,
	DV.Title AS DivisionName,
	--ISNULL(EmployeeId,0) AS EmployeeId,
	--ISNULL(SubjectId,0) AS SubjectId,
	--ISNULL(Em.FirstName,'') + ' '+ISNULL(em.LastName,'') AS EmployeeName,  
	--ISNULL(EM.ShortName,'') AS EmpShortName,
	--ISNULL(SM.Title,'') AS Subject,
	TTT.DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TTT.DayId,0) AS DayId,
	ISNULL(TTT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TTT.LectureNumber),'') AS DayLacture,
	--ISNULL(CL.Id,0) AS ClassId,
    ISNULL(DV.Code,'') AS ClassDivisionName
	,ISNULL(TTT.FromTime,'') AS FromTime
	,ISNULL(TTT.ToTime,'') AS ToTime
  
	FROM 
	--sTimetable.tTimeTable TT  
	sTimetable.tTimeTableTime TTT
	--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	--INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	INNER JOIN sCommon.tDayMaster DM ON DM.Id = TTT.DayId
	INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = TTT.DivisionId
	--INNER JOIN sSetup.tClassMaster CL ON CL.Id = DV.ClassId
	--LEFT JOIN sTimetable.tTimeTableTime TTT ON TTT.TimeTableSchemaId = TT.TimeTableSchemaId AND TTT.DivisionId = TT.DivisionId AND TTT.DayId = TT.DayId AND TTT.LectureNumber = TT.LectureNumber
	
	WHERE
	 --TT.TimeTableSchemaId=@rTimeTableSchemaId 
	 TTT.TimeTableSchemaId=@rTimeTableSchemaId
	--AND((EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
	  AND (TTT.DayId IN (SELECT CAST(item AS int) FROM  sCommon.fnsplit(@rDayIds,',')) OR (@rDayIds = ''))
	  AND ((TTT.LectureNumber = @rLectureNo) OR (@rLectureNo = 0))
	   AND ((DV.OrgId=@rOrgId) OR (@rOrgId=0))
	   --AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ISNULL(TTT.IsBreak,0)=0
	AND ISNULL(TTT.IsBreakBefore,0)=0
	AND ((ISNULL(TTT.DivisionId,0)=@rDivisionId) OR (@rDivisionId=0))
	order by TTT.LectureNumber
END
GO
PRINT N'Creating Procedure [sPurchase].[pGoodsReceivedNoteAdd]...';


GO





CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteAdd]
		@rId bigint,
		@rPurchaseRequestId bigint,
		@rPurchaseOrderId bigint,
		@rVendorId int,
		@rPODueDate datetime,	
		@rRequestedBy nvarchar(100),
		@rOrgGroupId smallint,
		@rLocationId int,
		@rStatusId smallint,	
		@rBillToAddress nvarchar(1000),
		@rUserId bigint,
		@rDetailList sPurchase.GoodsReceivedNoteDetailType READONLY,
		@rDocumentList sPurchase.DocumentManagementType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tGoodsReceivedNote
			set 
				StatusId = @rStatusId,
				PurchaseRequestId = @rPurchaseRequestId,
				PurchaseOrderId = @rPurchaseOrderId,
				VendorId = @rVendorId,
				PODueDate = @rPODueDate,
				BillToAddress = @rBillToAddress,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tGoodsReceivedNoteDetail
			where GoodsReceivedNoteId = @rId

			DECLARE @lNextNumberGRN INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNoteDetail',@lNextNumber = @lNextNumberGRN output
			set @lNextNumberGRN=@lNextNumberGRN-1
			INSERT INTO sPurchase.tGoodsReceivedNoteDetail
			(
				Id,
				OrgGroupId,
				GoodsReceivedNoteId,
				PurchaseRequestDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				PreviousGRNQty,
				UnitPrice,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberGRN+Id,
					OrgGroupId,
					@rId,
					PurchaseRequestDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					PreviousGRNQty,
					UnitPrice,
					Remark,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberGRN=@lNextNumberGRN+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tGoodsReceivedNoteDetail', @rCurrentNumber = @lNextNumberGRN

			INSERT INTO sPurchase.tDocumentManagement
			(
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl,
				CreatedUserId,
				CreatedDateTime
			)
			select	@rOrgGroupId,
					@rId,
					2043, 
					@rUserId,
					FileName,
					Size,
					DocumentUrl,
					@rUserId, 
					GETUTCDATE() 
			from @rDocumentList
			Select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNote',@lNextNumber = @lNextNumber output	
			--------------select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			--------------@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tGoodsReceivedNote
			(
				Id,
				GRNNumber,
				PurchaseRequestId,
				PurchaseOrderId,
				PODueDate,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				VendorId,
				BillToAddress,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rPurchaseRequestId,
				@rPurchaseOrderId,
				@rPODueDate,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rVendorId,
				@rBillToAddress,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberGRND INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNoteDetail',@lNextNumber = @lNextNumberGRND output	
			set @lNextNumberGRND=@lNextNumberGRND-1

	 		INSERT INTO sPurchase.tGoodsReceivedNoteDetail
			(
				Id,
				OrgGroupId,
				GoodsReceivedNoteId,
				PurchaseRequestDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				PreviousGRNQty,
				UnitPrice,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberGRND+Id,
					OrgGroupId,
					@rId,
					PurchaseRequestDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					PreviousGRNQty,
					UnitPrice,
					Remark,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberGRND=@lNextNumberGRND+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tGoodsReceivedNoteDetail', @rCurrentNumber = @lNextNumberGRND

			INSERT INTO sPurchase.tDocumentManagement
			(
				OrgGroupId,
				SourceId,
				SourceTypeId,
				UserId,
				FileName,
				Size,
				DocumentUrl,
				CreatedUserId,
				CreatedDateTime
			)
			select	@rOrgGroupId,
					@rId,
					2043, 
					@rUserId,
					FileName,
					Size,
					DocumentUrl,
					@rUserId, 
					GETUTCDATE() 
			from @rDocumentList
			select @rId

			Declare @typeId smallint=0
			Declare @Level smallint=0
			SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 4
			IF(@typeId = 1)
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,1,'',0,0,4,@rOrgGroupId
			END
			ELSE IF(@typeId = 2)
			Begin
				exec [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,1,'',1,@Level,4,@rOrgGroupId
			End
			ELSE IF(@typeId = 3)
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,3,'',0,0,4,@rOrgGroupId
			END
			--select 1;
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sStudent].[pImportStudent]...';


GO
ALTER PROCEDURE [sStudent].[pImportStudent] @rOrgGroupId SMALLINT
	,@rOrgId SMALLINT
	,@rXmldoc [nvarchar] (max)
	,@rUserId BIGINT
	,@rBatchId INT
	,@rOrgGroupBatchId INT
	,@rOperation INT = 0 --1 For Insert,2 For Update
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		DECLARE @lCount INT
		DECLARE @lInterrorCode INT
			,@intDoc INT
			,@lCode NVARCHAR(20)
			,@lNumber BIGINT
			,@lRegistrationNumber NVARCHAR(20)
			,@lFirstName NVARCHAR(100)
			,@lMiddleName NVARCHAR(100)
			,@lLastName NVARCHAR(100)
			,@lClassId INT
			,@lClass NVARCHAR(100)
			,@lDivisionId INT
			,@lDivision NVARCHAR(100)
			,@lRollNo INT
			,@lAdmissionStandardId INT
			,@lAdmissionStandard NVARCHAR(100)
			,@lAdmissionDate DATE
			,@lPreviousSchool NVARCHAR(200)
			,@lDOB DATE
			,@lGenderId INT = 0
			,@lGender NVARCHAR(10)
			,@lBloodGroupId INT = 0
			,@lBloodGroup NVARCHAR(10)
			,@lAdmissionCategoryId INT
			,--@lAdmissionCategory nvarchar(100),
			@lReligionId INT
			,@lReligion NVARCHAR(100)
			,@lFamilyCast NVARCHAR(100)
			,@lFamilySubCast NVARCHAR(100)
			,@lCastCategoryId INT = 0
			,@lCastCategory NVARCHAR(100)
			,@lParentContactNo NVARCHAR(20)
			,@lParentEmail NVARCHAR(50)
			,@lStudentContactNo NVARCHAR(20)
			,@lStudentEmail NVARCHAR(50)
			,@lPresentStreetOne NVARCHAR(150)
			,@lPresentStreetTwo NVARCHAR(150)
			,@lPresentStreetThree NVARCHAR(150)
			,@lPresentCity NVARCHAR(50)
			,@lPresentZipCode NVARCHAR(20)
			,@lPresentState NVARCHAR(50)
			,@lPresentCountry NVARCHAR(50)
			,@lPresentContactNo NVARCHAR(20)
			,
			--@lEmergencyStreetOne nvarchar(50),
			--@lEmergencyStreetTwo nvarchar(50),
			--@lEmergencyStreetThree nvarchar(50),
			--@lEmergencyCountry nvarchar(50),
			--@lEmergencyState nvarchar(50),
			--@lEmergencyCity nvarchar(50),
			--@lEmergencyZipCode nvarchar(20),
			@lEmergencyContactNo NVARCHAR(20)
			,@lBirthPlace NVARCHAR(150)
			,@lBirthTaluka NVARCHAR(150)
			,@lBirthDistrict NVARCHAR(150)
			,@lBirthDateInWord NVARCHAR(150)
			,@lHouseId INT
			,@lHouse NVARCHAR(100)
			,
			--@lMotherTongueId int,
			@lMotherTongue NVARCHAR(100)
			,@lAdhaarNumber NVARCHAR(20)
			,@lUIDNumber NVARCHAR(50)
			,@lQuotaId INT
			,@lQuota NVARCHAR(100)
			,
			-- New Add
			@lSUId NVARCHAR(50)
			,@lLeftStandardId INT
			,@lLeftStandard NVARCHAR(100)
			,@lLeftDate DATE
			,@lLCNumber NVARCHAR(20)
			,@lLCDate DATE
			,@lLCReason NVARCHAR(200)
			,@lLCProgress NVARCHAR(200)
			,@lLCConduct NVARCHAR(200)
			,@lLCRemark NVARCHAR(200)
			,@lStatusId SMALLINT
			,@lBirthState NVARCHAR(100)
			,@lBirthCountry NVARCHAR(100)
			,@lAcademicId BIGINT
			,@lPreviousStandard NVARCHAR(100)
			,@lWhatsAppContactNo NVARCHAR(20)
			,@lTribeId INT = 0
			,@lTribe NVARCHAR(100)
			,@lPreviousLeftDate DATE
		DECLARE @EmployeeId BIGINT
		--DECLARE @OutClassId int
		--DECLARE @OutDivisionId int
		DECLARE @OutStudentId BIGINT

		--DECLARE @OutAdmissionStandardId int
		--DECLARE @OutReligionId int
		--DECLARE @OutAdmissionCategoryId int		
		SET @lAdmissionCategoryId = sCommon.fGetIntIdForOrg(1, @rOrgGroupId)

		DECLARE @1StudentId BIGINT = 0

		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT
			,@rXmlDoc

		CREATE TABLE #tTable (
			Id BIGINT identity
			,Code NVARCHAR(20)
			,Number BIGINT
			,RegistrationNumber NVARCHAR(20)
			,FirstName NVARCHAR(100)
			,MiddleName NVARCHAR(100)
			,LastName NVARCHAR(100)
			,ClassId INT NULL
			,Class NVARCHAR(100)
			,DivisionId INT NULL
			,Division NVARCHAR(100)
			,RollNo INT
			,AdmissionStandardId INT
			,AdmissionStandard NVARCHAR(100)
			,AdmissionDate DATE
			,PreviousSchool NVARCHAR(200)
			,DOB DATE
			,GenderId INT NULL
			,Gender NVARCHAR(10)
			,BloodGroupId INT NULL
			,BloodGroup NVARCHAR(10)
			,ReligionId INT
			,Religion NVARCHAR(100)
			,
			--AdmissionCategoryId int,
			--AdmissionCategory nvarchar(100),
			FamilyCast NVARCHAR(100)
			,FamilySubCast NVARCHAR(100)
			,CastCategoryId INT
			,CastCategory NVARCHAR(100)
			,ParentContactNo NVARCHAR(20)
			,ParentEmail NVARCHAR(50)
			,StudentContactNo NVARCHAR(20)
			,StudentEmail NVARCHAR(50)
			,PresentStreetOne NVARCHAR(150)
			,PresentStreetTwo NVARCHAR(150)
			,PresentStreetThree NVARCHAR(150)
			,PresentCity NVARCHAR(50)
			,PresentZipCode NVARCHAR(20)
			,PresentState NVARCHAR(50)
			,PresentCountry NVARCHAR(50)
			,PresentContactNo NVARCHAR(20)
			,
			--EmergencyStreetOne nvarchar(50),
			--EmergencyStreetTwo nvarchar(50),
			--EmergencyStreetThree nvarchar(50),
			--EmergencyCountry nvarchar(50),
			--EmergencyState nvarchar(50),
			--EmergencyCity nvarchar(50),
			--EmergencyZipCode nvarchar(20),
			EmergencyContactNo NVARCHAR(20)
			,BirthPlace NVARCHAR(150)
			,BirthTaluka NVARCHAR(150)
			,BirthDistrict NVARCHAR(150)
			,BirthDateInWord NVARCHAR(150)
			,CreatedUserId BIGINT
			,HouseId INT
			,House NVARCHAR(100)
			,MotherTongueId INT
			,MotherTongue NVARCHAR(100)
			,AdhaarNumber NVARCHAR(20)
			,UIDNumber NVARCHAR(50)
			,QuotaId INT
			,Quota NVARCHAR(100)
			,SUId NVARCHAR(50)
			,LeftStandardId INT
			,LeftStandard NVARCHAR(100)
			,LeftDate DATE
			,LCNumber NVARCHAR(20)
			,LCDate DATE
			,LCReason NVARCHAR(200)
			,LCProgress NVARCHAR(200)
			,LCConduct NVARCHAR(200)
			,LCRemark NVARCHAR(200)
			,StatusId SMALLINT
			,BirthState NVARCHAR(100)
			,BirthCountry NVARCHAR(100)
			,PreviousStandard NVARCHAR(100)
			,WhatsAppContactNo NVARCHAR(20)
			,TribeId INT NULL
			,Tribe NVARCHAR(100)
			,PreviousLeftDate DATE
			)

		INSERT INTO #tTable (
			Code
			,Number
			,RegistrationNumber
			,FirstName
			,MiddleName
			,LastName
			,ClassId
			,Class
			,DivisionId
			,Division
			,RollNo
			,AdmissionStandardId
			,AdmissionStandard
			,AdmissionDate
			,PreviousSchool
			,DOB
			,GenderId
			,Gender
			,BloodGroupId
			,BloodGroup
			,ReligionId
			,Religion
			,
			--AdmissionCategoryId,
			--AdmissionCategory,
			FamilyCast
			,FamilySubCast
			,CastCategoryId
			,CastCategory
			,ParentContactNo
			,ParentEmail
			,StudentContactNo
			,StudentEmail
			,PresentStreetOne
			,PresentStreetTwo
			,PresentStreetThree
			,PresentCity
			,PresentZipCode
			,PresentState
			,PresentCountry
			,PresentContactNo
			,
			--EmergencyStreetOne,
			--EmergencyStreetTwo,
			--EmergencyStreetThree,
			--EmergencyCountry,
			--EmergencyState,
			--EmergencyCity,
			--EmergencyZipCode,
			EmergencyContactNo
			,BirthPlace
			,BirthTaluka
			,BirthDistrict
			,BirthDateInWord
			,CreatedUserId
			,HouseId
			,House
			,MotherTongueId
			,MotherTongue
			,AdhaarNumber
			,UIDNumber
			,QuotaId
			,Quota
			,SUId
			,LeftStandardId
			,LeftStandard
			,LeftDate
			,LCNumber
			,LCDate
			,LCReason
			,LCProgress
			,LCConduct
			,LCRemark
			,StatusId
			,BirthState
			,BirthCountry
			,PreviousStandard
			,WhatsAppContactNo
			,TribeId
			,Tribe
			,PreviousLeftDate
			)
		SELECT Code
			,Number
			,RegistrationNumber
			,sSetup.fPortalXMLTagsReplaceReverse(FirstName) AS FirstName
			,sSetup.fPortalXMLTagsReplaceReverse(MiddleName) AS MiddleName
			,sSetup.fPortalXMLTagsReplaceReverse(LastName) AS LastName
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Class) AS Class
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Division) AS Division
			,RollNo
			,0
			,AdmissionStandard
			,AdmissionDate
			,sSetup.fPortalXMLTagsReplaceReverse(PreviousSchool) AS PreviousSchool
			,DOB
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Gender) AS Gender
			,0
			,BloodGroup
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Religion) AS Religion
			,
			--0,
			--AdmissionCategory,
			sSetup.fPortalXMLTagsReplaceReverse(FamilyCast) AS FamilyCast
			,sSetup.fPortalXMLTagsReplaceReverse(FamilySubCast) AS FamilySubCast
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(CastCategory) AS CastCategory
			,ParentContactNo
			,ParentEmail
			,StudentContactNo
			,StudentEmail
			,sSetup.fPortalXMLTagsReplaceReverse(PresentStreetOne) AS PresentStreetOne
			,sSetup.fPortalXMLTagsReplaceReverse(PresentStreetTwo) AS PresentStreetTwo
			,sSetup.fPortalXMLTagsReplaceReverse(PresentStreetThree) AS PresentStreetThree
			,sSetup.fPortalXMLTagsReplaceReverse(PresentCity) AS PresentCity
			,PresentZipCode
			,sSetup.fPortalXMLTagsReplaceReverse(PresentState) AS PresentState
			,sSetup.fPortalXMLTagsReplaceReverse(PresentCountry) AS PresentCountry
			,PresentContactNo
			,
			--EmergencyStreetOne,
			--EmergencyStreetTwo,
			--EmergencyStreetThree,
			--EmergencyCountry,
			--EmergencyState,
			--EmergencyCity,
			--EmergencyZipCode,
			EmergencyContactNo
			,sSetup.fPortalXMLTagsReplaceReverse(BirthPlace) AS BirthPlace
			,sSetup.fPortalXMLTagsReplaceReverse(BirthTaluka) AS BirthTaluka
			,sSetup.fPortalXMLTagsReplaceReverse(BirthDistrict) AS BirthDistrict
			,sSetup.fPortalXMLTagsReplaceReverse(BirthDateInWord) AS BirthDateInWord
			,CreatedUserId
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(House) AS House
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(MotherTongue) AS MotherTongue
			,sSetup.fPortalXMLTagsReplaceReverse(AdhaarNumber) AS AdhaarNumber
			,UIDNumber
			,0
			,Quota
			,SUId
			,0
			,LeftStandard
			,LeftDate
			,LCNumber
			,LCDate
			,sSetup.fPortalXMLTagsReplaceReverse(LCReason) AS LCReason
			,LCProgress
			,LCConduct
			,sSetup.fPortalXMLTagsReplaceReverse(LCRemark) AS LCRemark
			,StatusId
			,sSetup.fPortalXMLTagsReplaceReverse(BirthState) AS BirthState
			,sSetup.fPortalXMLTagsReplaceReverse(BIrthCountry) AS BIrthCountry
			,PreviousStandard
			,WhatsAppContactNo
			,0
			,Tribe
			,PreviousLeftDate
		FROM OPENXML(@intDoc, '/Table/ImportStudent', 1) WITH (
				Code NVARCHAR(20) '@Code'
				,Number BIGINT '@Number'
				,RegistrationNumber NVARCHAR(20) '@RegistrationNumber'
				,FirstName NVARCHAR(100) '@FirstName'
				,MiddleName NVARCHAR(100) '@MiddleName'
				,LastName NVARCHAR(100) '@LastName'
				,Class NVARCHAR(100) '@Class'
				,Division NVARCHAR(100) '@Division'
				,RollNo INT '@RollNo'
				,AdmissionStandard NVARCHAR(100) '@AdmissionStandard'
				,AdmissionDate DATE '@AdmissionDate'
				,PreviousSchool NVARCHAR(200) '@PreviousSchool'
				,DOB DATE '@DOB'
				,Gender NVARCHAR(10) '@Gender'
				,BloodGroup NVARCHAR(10) '@BloodGroup'
				,Religion NVARCHAR(100) '@Religion'
				,
				--AdmissionCategory nvarchar(100) '@AdmissionCategory',
				FamilyCast NVARCHAR(100) '@FamilyCast'
				,FamilySubCast NVARCHAR(100) '@FamilySubCast'
				,CastCategory NVARCHAR(100) '@CastCategory'
				,ParentContactNo NVARCHAR(20) '@ParentContactNo'
				,ParentEmail NVARCHAR(50) '@ParentEmail'
				,StudentContactNo NVARCHAR(20) '@StudentContactNo'
				,StudentEmail NVARCHAR(50) '@StudentEmail'
				,PresentStreetOne NVARCHAR(150) '@PresentStreetOne'
				,PresentStreetTwo NVARCHAR(150) '@PresentStreetTwo'
				,PresentStreetThree NVARCHAR(150) '@PresentStreetThree'
				,PresentCity NVARCHAR(50) '@PresentCity'
				,PresentZipCode NVARCHAR(20) '@PresentZipCode'
				,PresentState NVARCHAR(50) '@PresentState'
				,PresentCountry NVARCHAR(50) '@PresentCountry'
				,PresentContactNo NVARCHAR(20) '@PresentContactNo'
				,
				--EmergencyStreetOne nvarchar(50) '@EmergencyStreetOne',
				--EmergencyStreetTwo nvarchar(50) '@EmergencyStreetTwo',
				--EmergencyStreetThree nvarchar(50) '@EmergencyStreetThree',
				--EmergencyCountry nvarchar(50) '@EmergencyCountry',
				--EmergencyState nvarchar(50) '@EmergencyState',
				--EmergencyCity nvarchar(50) '@EmergencyCity',
				--EmergencyZipCode nvarchar(20) '@EmergencyZipCode',
				EmergencyContactNo NVARCHAR(20) '@EmergencyContactNo'
				,BirthPlace NVARCHAR(150) '@BirthPlace'
				,BirthTaluka NVARCHAR(150) '@BirthTaluka'
				,BirthDistrict NVARCHAR(150) '@BirthDistrict'
				,BirthDateInWord NVARCHAR(150) '@BirthDateInWord'
				,CreatedUserId BIGINT '@CreatedUserId'
				,House NVARCHAR(100) '@House'
				,MotherTongue NVARCHAR(100) '@MotherTongue'
				,AdhaarNumber NVARCHAR(20) '@AdhaarNumber'
				,UIDNumber NVARCHAR(50) '@UIDNumber'
				,Quota NVARCHAR(20) '@Quota'
				,SUId NVARCHAR(50) '@SUId'
				,LeftStandard NVARCHAR(100) '@LeftStandard'
				,LeftDate DATE '@LeftDate'
				,LCNumber NVARCHAR(20) '@LCNumber'
				,LCDate DATE '@LCDate'
				,LCReason NVARCHAR(200) '@LCReason'
				,LCProgress NVARCHAR(200) '@LCProgress'
				,LCConduct NVARCHAR(200) '@LCConduct'
				,LCRemark NVARCHAR(200) '@LCRemark'
				,StatusId SMALLINT '@StatusId'
				,BirthState NVARCHAR(100) '@BirthState'
				,BirthCountry NVARCHAR(100) '@BirthCountry'
				,PreviousStandard NVARCHAR(100) '@PreviousStandard'
				,WhatsAppContactNo NVARCHAR(20) '@WhatsAppContactNo'
				,Tribe NVARCHAR(100) '@Tribe'
				,PreviousLeftDate DATE '@PreviousLeftDate'
				)

		EXEC sp_xml_removedocument @intDoc

		SELECT @lCount = COUNT(Id)
		FROM #tTable

		WHILE @lCount > 0
		BEGIN
			SET @lCode = ''
			SET @lNumber = NULL
			SET @lRegistrationNumber = NULL
			SET @lFirstName = ''
			SET @lMiddleName = ''
			SET @lLastName = ''
			SET @lClassId = NULL
			SET @lClass = ''
			SET @lDivisionId = NULL
			SET @lDivision = ''
			SET @lRollNo = NULL
			SET @lAdmissionStandardId = NULL
			SET @lAdmissionStandard = ''
			SET @lAdmissionDate = ''
			SET @lPreviousSchool = ''
			SET @lDOB = ''
			SET @lGenderId = NULL
			SET @lGender = ''
			SET @lBloodGroupId = NULL
			SET @lBloodGroup = ''
			SET @lReligionId = NULL
			SET @lReligion = ''
			--SET @lAdmissionCategoryId  = null
			--SET @lAdmissionCategory = ''
			SET @lFamilyCast = ''
			SET @lFamilySubCast = ''
			SET @lCastCategoryId = NULL
			SET @lCastCategory = ''
			SET @lParentContactNo = ''
			SET @lParentEmail = ''
			SET @lStudentContactNo = ''
			SET @lStudentEmail = ''
			SET @lPresentStreetOne = ''
			SET @lPresentStreetTwo = ''
			SET @lPresentStreetThree = ''
			SET @lPresentCity = ''
			SET @lPresentZipCode = ''
			SET @lPresentState = ''
			SET @lPresentCountry = ''
			SET @lPresentContactNo = ''
			--SET @lEmergencyStreetOne = ''
			--SET @lEmergencyStreetTwo = ''
			--SET @lEmergencyStreetThree = ''
			--SET @lEmergencyCountry = ''
			--SET @lEmergencyState = ''
			--SET @lEmergencyCity = ''
			--SET @lEmergencyZipCode = ''
			SET @lEmergencyContactNo = ''
			SET @lBirthPlace = ''
			SET @lBirthTaluka = ''
			SET @lBirthDistrict = ''
			SET @lBirthDateInWord = ''
			--SET @OutClassId = null
			--SET @OutDivisionId = null
			SET @OutStudentId = NULL
			--SET @OutAdmissionStandardId = null
			--SET @OutReligionId = null,
			SET @lHouseId = NULL
			SET @lHouse = ''
			--SET @lMotherTongueId=NULL
			SET @lMotherTongue = ''
			SET @lAdhaarNumber = ''
			SET @lUIDNumber = ''
			SET @lQuotaId = NULL
			SET @lQuota = ''
			SET @lSUId = ''
			SET @lLeftStandardId = NULL
			SET @lLeftStandard = ''
			SET @lLeftDate = ''
			SET @lLCNumber = ''
			SET @lLCDate = ''
			SET @lLCReason = ''
			SET @lLCProgress = ''
			SET @lLCConduct = ''
			SET @lLCRemark = ''
			SET @lStatusId = NULL
			SET @lBirthState = ''
			SET @lBirthCountry = ''
			SET @lPreviousStandard = ''
			SET @lWhatsAppContactNo = ''
			SET @lTribeId = NULL
			SET @lTribe = ''
			SET @lPreviousLeftDate = ''

			SELECT @lCode = Code
				,@lNumber = Number
				,@lRegistrationNumber = RegistrationNumber
				,@lFirstName = FirstName
				,@lMiddleName = MiddleName
				,@lLastName = LastName
				,@lClass = Class
				,@lDivision = Division
				,@lRollNo = RollNo
				,@lAdmissionStandard = AdmissionStandard
				,@lAdmissionDate = CASE 
					WHEN AdmissionDate = ''
						THEN NULL
					ELSE AdmissionDate
					END
				,@lPreviousSchool = PreviousSchool
				,@lReligion = Religion
				,
				--@lAdmissionCategory = AdmissionCategory,
				@lFamilyCast = FamilyCast
				,@lFamilySubCast = FamilySubCast
				,@lCastCategory = CastCategory
				,@lDOB = CASE 
					WHEN DOB = ''
						THEN NULL
					ELSE DOB
					END
				,@lGender = Gender
				,@lBloodGroup = BloodGroup
				,@lParentContactNo = ParentContactNo
				,@lParentEmail = ParentEmail
				,@lStudentContactNo = StudentContactNo
				,@lStudentEmail = StudentEmail
				,@lPresentStreetOne = PresentStreetOne
				,@lPresentStreetTwo = PresentStreetTwo
				,@lPresentStreetThree = PresentStreetThree
				,@lPresentCountry = PresentCountry
				,@lPresentState = PresentState
				,@lPresentCity = PresentCity
				,@lPresentZipCode = PresentZipCode
				,@lPresentContactNo = PresentContactNo
				,
				--@lEmergencyStreetOne = EmergencyStreetOne,
				--@lEmergencyStreetTwo = EmergencyStreetTwo,
				--@lEmergencyStreetThree = EmergencyStreetThree,
				--@lEmergencyCountry = EmergencyCountry,
				--@lEmergencyState = EmergencyState,
				--@lEmergencyCity = EmergencyCity,
				--@lEmergencyZipCode = EmergencyZipCode,
				@lEmergencyContactNo = EmergencyContactNo
				,@lBirthPlace = BirthPlace
				,@lBirthTaluka = BirthTaluka
				,@lBirthDistrict = BirthDistrict
				,@lBirthDateInWord = BirthDateInWord
				,@lHouse = House
				,@lMotherTongue = MotherTongue
				,@lAdhaarNumber = AdhaarNumber
				,@lUIDNumber = UIDNumber
				,@lSUId = SUId
				,@lLeftStandard = LeftStandard
				,@lLeftDate = CASE 
					WHEN LeftDate = ''
						THEN NULL
					ELSE LeftDate
					END
				,@lLCNumber = LCNumber
				,@lLCDate = CASE 
					WHEN LCDate = ''
						THEN NULL
					ELSE LCDate
					END
				,@lLCReason = LCReason
				,@lLCProgress = LCProgress
				,@lLCConduct = LCConduct
				,@lLCRemark = LCRemark
				,@lStatusId = StatusId
				,@lBirthState = BirthState
				,@lBirthCountry = BirthCountry
				,@lPreviousStandard = PreviousStandard
				,@lWhatsAppContactNo = WhatsAppContactNo
				,@lTribe = Tribe
				,@lPreviousLeftDate = CASE 
					WHEN PreviousLeftDate = ''
						THEN NULL
					ELSE PreviousLeftDate
					END
			FROM #tTable
			WHERE Id = @lCount

			SELECT @lGenderId = ID
			FROM sCommon.tGenderMaster
			WHERE Title = @lGender

			SELECT @lLeftStandardId = ID
			FROM sSetup.tClassMaster
			WHERE Title = @lLeftStandard
				AND OrgId = @rOrgId

			SELECT @lClassId = ID
			FROM sSetup.tClassMaster
			WHERE Title = @lClass
				AND OrgId = @rOrgId

			SELECT @lDivisionId = ID
			FROM sSetup.tDivisionMaster
			WHERE Title = @lDivision
				AND ClassId = @lClassId
				AND OrgId = @rOrgId

			SELECT @lBloodGroupId = ID
			FROM sCommon.tBloodGroupMaster
			WHERE Title = @lBloodGroup

			SELECT @lAdmissionStandardId = ID
			FROM sSetup.tClassMaster
			WHERE Title = @lAdmissionStandard
				AND OrgId = @rOrgId

			SELECT @lReligionId = ID
			FROM sCommon.tReligionMaster
			WHERE Title = @lReligion
				AND OrgGroupId = @rOrgGroupId

			--SELECT	@lAdmissionCategoryId  = ID FROM tAdmissionCategoryMaster WHERE Title = @lAdmissionCategory AND OrgGroupId = @rOrgGroupId
			SELECT @lCastCategoryId = ID
			FROM sCommon.tCastCategoryMaster
			WHERE Title = @lCastCategory
				AND OrgGroupId = @rOrgGroupId

			SELECT @lHouseId = ID
			FROM sActivity.tHouseMaster
			WHERE Title = @lHouse
				AND OrgId = @rOrgId

			SELECT @lQuotaId = ID
			FROM sCommon.tQuotaMaster
			WHERE Title = @lQuota
				AND OrgGroupId = @rOrgGroupId

			--SELECT	@lMotherTongueId  = ID FROM sCommon.tMotherTongueMaster WHERE Title = @lMotherTongue
			SELECT @lTribeId = ID
			FROM sCommon.tTribeMaster
			WHERE Title = @lTribe

			PRINT (@lTribeId)

			IF (@lGenderId IS NULL)
				SET @lGenderId = 0

			IF (@lBloodGroupId IS NULL)
				SET @lBloodGroupId = 0

			IF (@lCastCategoryId IS NULL)
				SET @lCastCategoryId = 0

			IF (@lHouseId IS NULL)
				SET @lHouseId = 0

			IF (@lQuotaId IS NULL)
				SET @lQuotaId = 0

			IF (@lTribeId IS NULL)
				SET @lTribeId = 0

			--IF(@lMotherTongueId IS NULL)
			--	SET	@lMotherTongueId = 0		
			--IF 	@lClassId IS NULL  AND @lClass != ''
			--BEGIN
			--	EXEC [sSetup].[pClassMasterAdd] 0,@lClass,@lClass,@lClass,@lClass,1,0,0,0,@rUserId,@rUserId,@rOrgId,@OutClassId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutClassId = @lClassId
			--END
			--IF 	@lAdmissionStandardId IS NULL  AND @lAdmissionStandard != ''
			--BEGIN
			--	EXEC [sSetup].[pClassMasterAdd] 0,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,1,0,0,0,@rUserId,@rUserId,@rOrgId,0,@OutAdmissionStandardId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutAdmissionStandardId = @lAdmissionStandardId
			--END
			--IF 	@lDivisionId IS NULL  AND @lDivision != ''
			--BEGIN
			--	SET @EmployeeId = sCommon.fGetBigIntIdForOrg(1,@rOrgId)
			--	EXEC [sSetup].[pDivisionMasterAdd] 0,@lDivision,@lDivision,@lDivision,@lClassId,@EmployeeId,NULL,0,@rUserId,@rUserId,0,@rOrgId,@OutDivisionId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutDivisionId = @lDivisionId
			--END
			--IF 	@lReligionId IS NULL  AND @lReligion != ''
			--BEGIN
			--	EXEC [sCommon].[pReligionMasterAdd] 0,@lReligion,@lReligion,0,@rUserId,@rOrgId,@OutReligionId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutReligionId = @lReligionId
			--END
			--IF 	@lAdmissionCategoryId IS NULL  AND @lAdmissionCategory != ''
			--BEGIN
			--	EXEC [sStudent].[pAdmissionCategoryMasterAdd] 0,@lAdmissionCategory,@lAdmissionCategory,0,@rUserId,@rOrgId,@OutAdmissionCategoryId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutAdmissionCategoryId = @lAdmissionCategoryId
			--END
			BEGIN TRANSACTION

			DECLARE @lStudCap INT
				,@lOrgStudentCap INT

			SELECT @lStudCap = ISNULL(NoOfStudent, 0) + ISNULL(StudentExtraCap, 0)
			FROM sSetup.tOrgGroupSetting
			WHERE OrgGroupId = @rOrgGroupId

			SELECT @lOrgStudentCap = [sSetup].[fStudentCapGet](@rOrgGroupBatchId)

			IF (@lOrgStudentCap >= @lStudCap)
			BEGIN
				SELECT - 111 AS RESULT

				COMMIT TRANSACTION

				RETURN
			END

			IF (
					@rOperation = 1
					OR @rOperation = 0
					)
			BEGIN
				IF (@lStatusId = 1)
					EXEC sStudent.pStudentMasterAdd 0
						,@lCode
						,@lRegistrationNumber
						,@lNumber
						,@lFirstName
						,@lMiddleName
						,@lLastName
						,@rOrgId
						,@lAdmissionCategoryId
						,1
						,502
						,@rUserId
						,@rUserId
						,@rOrgGroupBatchId
						,@OutStudentId OUTPUT
						,@lSUId
				ELSE
					EXEC sStudent.pStudentMasterAdd 0
						,@lCode
						,@lRegistrationNumber
						,@lNumber
						,@lFirstName
						,@lMiddleName
						,@lLastName
						,@rOrgId
						,@lAdmissionCategoryId
						,3
						,502
						,@rUserId
						,@rUserId
						,@rOrgGroupBatchId
						,@OutStudentId OUTPUT
						,@lSUId

				EXEC sStudent.pAcademicAdd 0
					,@OutStudentId
					,@lClassId
					,@lDivisionId
					,@lRollNo
					,@rOrgId
					,@rBatchId
					,@rUserId
					,@rUserId
					,@lAdmissionCategoryId
					,1

				EXEC sStudent.pStudentCommunicationAdd @OutStudentId
					,@lPresentStreetOne
					,@lPresentStreetTwo
					,@lPresentStreetThree
					,@lPresentCountry
					,@lPresentState
					,@lPresentCity
					,@lPresentZipCode
					,@lPresentContactNo
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,@lEmergencyContactNo
					,@lParentContactNo
					,@lParentEmail
					,@lStudentContactNo
					,@lStudentEmail
					,@rUserId
					,@rUserId
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,@lWhatsAppContactNo

				EXEC sStudent.pStudentOtherAdd @OutStudentId
					,@lUIDNumber
					,@lDOB
					,@lGenderId
					,@lReligionId
					,@lBloodGroupId
					,@lBirthPlace
					,@lBirthTaluka
					,@lBirthDistrict
					,@lBirthDateInWord
					,@lFamilyCast
					,@lFamilySubCast
					,@lCastCategoryId
					,NULL
					,@lHouseId
					,NULL
					,NULL
					,''
					,@rUserId
					,@rUserId
					,''
					,@lAdhaarNumber
					,@lMotherTongue
					,@lQuotaId
					,@lBirthState
					,@lBirthCountry
					,@rBatchId
					,@lTribeId

				IF (@lStatusId = 1)
					EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId
						,@lPreviousSchool
						,NULL
						,NULL
						,NULL
						,NULL
						,@lAdmissionStandardId
						,@lAdmissionDate
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@rBatchId
						,@rUserId
						,@rUserId
						,1
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lPreviousStandard
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lPreviousLeftDate
				ELSE
					EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId
						,@lPreviousSchool
						,NULL
						,NULL
						,NULL
						,NULL
						,@lAdmissionStandardId
						,@lAdmissionDate
						,NULL
						,@lLeftStandardId
						,@lLeftDate
						,NULL
						,NULL
						,NULL
						,@lLCReason
						,@lLCProgress
						,@lLCConduct
						,NULL
						,@lLCNumber
						,@lLCDate
						,@lLCRemark
						,NULL
						,NULL
						,@rBatchId
						,@rUserId
						,@rUserId
						,0
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lPreviousStandard
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lPreviousLeftDate
			END
			ELSE
			BEGIN
				SET @1StudentId = (
						SELECT Id
						FROM sStudent.tStudentMaster
						WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT
							AND OrgId = @rOrgId
						)

				UPDATE sStudent.tStudentMaster
				SET RegistrationNumber = @lRegistrationNumber
					,FirstName = @lFirstName
					,MiddleName = @lMiddleName
					,LastName = @lLastName
					,SUId = @lSUId
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
				WHERE Id = @1StudentId

				UPDATE sStudent.tStudentAdmission
				SET AdmissionStandardId = @lAdmissionStandardId
					,AdmissionDate = @lAdmissionDate
					,PreviousSchool = @lPreviousSchool
					,LeftStandardId = @lLeftStandardId
					,LeftDate = @lLeftDate
					,LCNumber = @lLCNumber
					,LCDate = @lLCDate
					,LCRemark = @lLCRemark
					,LCConduct = @lLCConduct
					,LCProgress = @lLCProgress
					,LeftReason = @lLCReason
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
					,PreviousStandard = @lPreviousStandard
					,PreviousLeftDate = @lPreviousLeftDate
				WHERE StudentId = @1StudentId

				UPDATE sStudent.tStudentOther
				SET DateOfBirth = @lDOB
					,GenderId = @lGenderId
					,BloodGroupId = @lBloodGroupId
					,ReligionId = @lReligionId
					,FamilyCast = @lFamilyCast
					,FamilySubCast = @lFamilySubCast
					,CastCategoryId = @lCastCategoryId
					,BirthPlace = @lBirthPlace
					,BirthTaluka = @lBirthTaluka
					,BirthDistrict = @lBirthDistrict
					,BirthState = @lBirthState
					,BirthCountry = @lBirthCountry
					,AdhaarNumber = @lAdhaarNumber
					,MotherTongue = @lMotherTongue
					,QuotaId = @lQuotaId
					,UIDNumber = @lUIDNumber
					,HouseId = @lHouseId
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
					,TribeId = @lTribeId
				WHERE StudentId = @1StudentId

				IF (@lDivisionId <> NULL)
				BEGIN
					UPDATE sStudent.tAcademic
					SET DivisionId = @lDivisionId
						,RollNo = @lRollNo
						,UpdatedUserId = @rUserId
						,UpdatedDateTime = getdate()
					WHERE StudentId = @1StudentId
						AND BatchId = @rBatchId
						AND OrgId = @rOrgId
				END

				UPDATE sStudent.tStudentCommunication
				SET PresentStreetOne = @lPresentStreetOne
					,PresentStreetTwo = @lPresentStreetTwo
					,PresentStreetThree = @lPresentStreetThree
					,PresentCountry = @lPresentCountry
					,PresentState = @lPresentState
					,PresentCity = @lPresentCity
					,PresentZipCode = @lPresentZipCode
					,PresentContactNo = @lPresentContactNo
					,EmergencyContactNo = @lEmergencyContactNo
					,ParentContactNo = @lParentContactNo
					,ParentEmail = @lParentEmail
					,StudentContactNo = @lStudentContactNo
					,StudentEmail = @lStudentEmail
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
				WHERE StudentId = @1StudentId
			END

			SET @lCount = @lCount - 1

			COMMIT TRANSACTION
		END

		SELECT 1
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT ERROR_MESSAGE()
			,ERROR_LINE()
	END CATCH
END
GO
PRINT N'Refreshing Procedure [sStudent].[pForceStudentDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pForceStudentDelete]';


GO
PRINT N'Refreshing Procedure [sCertificate].[pOverallCertificateCountGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pOverallCertificateCountGet]';


GO
PRINT N'Refreshing Procedure [sCertificate].[pSummaryCountGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pSummaryCountGet]';


GO
PRINT N'Refreshing Procedure [sCommon].[pOrganizationSetupRemove]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pOrganizationSetupRemove]';


GO
PRINT N'Refreshing Procedure [sCertificate].[pTemplateFunctionalFieldsGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pTemplateFunctionalFieldsGet]';


GO
PRINT N'Refreshing Procedure [sSetup].[pOrganizationWiseStudentDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSetup].[pOrganizationWiseStudentDelete]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pXMLCircularAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pXMLCircularAdd]';


GO
PRINT N'Refreshing Procedure [sErp].[pOrgGroupModuleSummaryGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sErp].[pOrgGroupModuleSummaryGet]';


GO
PRINT N'Refreshing Procedure [sAlert].[pCircularSchedulerGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pCircularSchedulerGet]';


GO
PRINT N'Refreshing Procedure [sAlert].[pNotificationLogGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pNotificationLogGet]';


GO
PRINT N'Refreshing Procedure [sCommon].[pDeleteOldBatchData]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pDeleteOldBatchData]';


GO
PRINT N'Refreshing Procedure [sCommon].[pOrgGroupSetupRemove]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pOrgGroupSetupRemove]';


GO
PRINT N'Refreshing Procedure [sCommon].[pPortalBatchSetupRemove]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pPortalBatchSetupRemove]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pCircularAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pCircularAdd]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pCircularApprove]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pCircularApprove]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pCircularDashboardGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pCircularDashboardGet]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pCircularDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pCircularDelete]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pCircularListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pCircularListGet]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pCircularQueueGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pCircularQueueGet]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pCircularTypeMasterDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pCircularTypeMasterDelete]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pDailyFeedGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pDailyFeedGet]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pMyDashboardNotificationGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pMyDashboardNotificationGet]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pVoiceRecognitionGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pVoiceRecognitionGet]';


GO
PRINT N'Refreshing Procedure [sSecurity].[pDashletGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSecurity].[pDashletGet]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pDailyThoughtAssignGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pDailyThoughtAssignGet]';


GO
PRINT N'Refreshing Procedure [sPurchase].[pGoodsReceivedNoteDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPurchase].[pGoodsReceivedNoteDelete]';


GO
PRINT N'Refreshing Procedure [sPurchase].[pGoodsReceivedNoteSearchSRGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPurchase].[pGoodsReceivedNoteSearchSRGet]';


GO
PRINT N'Refreshing Procedure [sWf].[pWfApprovalGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWf].[pWfApprovalGet]';


GO
PRINT N'Refreshing Procedure [sAssessment].[pSiddhiKrupaFieldsGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAssessment].[pSiddhiKrupaFieldsGet]';


GO
PRINT N'Refreshing Procedure [sStudent].[pImportStudent_New]...';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pImportStudent_New]';


GO
PRINT N'Refreshing Procedure [sStudent].[pStudentViewProfileGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentViewProfileGet]';


GO
PRINT N'Refreshing Procedure [sStudent].[pStudentDetailFormGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDetailFormGet]';


GO
PRINT N'Update complete.';


GO



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

