

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




GO
CREATE SCHEMA [sEMeeting]
    AUTHORIZATION [dbo];


GO
PRINT N'Creating Schema [sPurchase]...';


GO
CREATE SCHEMA [sPurchase]
    AUTHORIZATION [dbo];


GO
PRINT N'Creating Schema [sWf]...';


GO
CREATE SCHEMA [sWf]
    AUTHORIZATION [dbo];


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


GO
CREATE TYPE [sEMeeting].[OnlineMeetingResourceDetailType] AS TABLE (
    [AutoId]          BIGINT          NOT NULL,
    [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   NULL,
    [OnlineMeetingId]   BIGINT   NOT NULL,
    [ScopeSourceTypeId] SMALLINT NOT NULL,
    [ScopeSourceId]     BIGINT   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].[OnlineMeetingReferenceDetailType]...';


GO
CREATE TYPE [sEMeeting].[OnlineMeetingReferenceDetailType] AS TABLE (
    [AutoId]          BIGINT          NOT NULL,
    [OnlineMeetingId] BIGINT          NOT NULL,
    [ReferencePath]   NVARCHAR (1000) NOT 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,
    [PurchaseOrderId]         BIGINT          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,
    [PurchaseRequestId] BIGINT          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,
    [QualityCheckId]            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,
    [ReasonForRejection]        NVARCHAR (300)  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,
    [SalesReturnId]             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,
    [RejectedQty]               DECIMAL (12, 2) NOT NULL,
    [CreditNoteIssueDate]       DATETIME        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,
    [QuotationRequestId]      BIGINT          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].[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,
    [ReasonForRejection]        NVARCHAR (300)  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,
    [GoodsReceivedNoteId]     BIGINT          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'Starting rebuilding table [sAlert].[tAlertQueueLog]...';


GO
BEGIN TRANSACTION;

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

CREATE TABLE [sAlert].[tmp_ms_xx_tAlertQueueLog] (
    [AutoId]          BIGINT         NOT NULL,
    [MessageDate]     DATETIME       NOT NULL,
    [QueueMessage]    NVARCHAR (MAX) NOT NULL,
    [EventId]         INT            NOT NULL,
    [AlertModeId]     TINYINT        NOT NULL,
    [OrgId]           SMALLINT       NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    CONSTRAINT [tmp_ms_xx_constraint_PK_tAlertQueueLog1] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);

IF EXISTS (SELECT TOP 1 1 
           FROM   [sAlert].[tAlertQueueLog])
    BEGIN
        INSERT INTO [sAlert].[tmp_ms_xx_tAlertQueueLog] ([AutoId], [MessageDate], [QueueMessage], [EventId], [AlertModeId], [OrgId], [CreatedUserId], [CreatedDateTime])
        SELECT   [AutoId],
                 [MessageDate],
                 [QueueMessage],
                 [EventId],
                 [AlertModeId],
                 [OrgId],
                 [CreatedUserId],
                 [CreatedDateTime]
        FROM     [sAlert].[tAlertQueueLog]
        ORDER BY [AutoId] ASC;
    END

DROP TABLE [sAlert].[tAlertQueueLog];

EXECUTE sp_rename N'[sAlert].[tmp_ms_xx_tAlertQueueLog]', N'tAlertQueueLog';

EXECUTE sp_rename N'[sAlert].[tmp_ms_xx_constraint_PK_tAlertQueueLog1]', N'PK_tAlertQueueLog', N'OBJECT';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Altering Table [sStudent].[tStudentAdmission]...';


GO
ALTER TABLE [sStudent].[tStudentAdmission]
    ADD [PreviousLeftDate] DATE NULL;


GO
PRINT N'Creating Table [sEMeeting].[tOnlineMeetingAttendance]...';


GO
CREATE TABLE [sEMeeting].[tOnlineMeetingAttendance] (
    [AutoId]                  BIGINT   IDENTITY (1, 1) NOT NULL,
    [OnlineLearningId]        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 [PK_tOnlineMeetingAttendance] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sEMeeting].[tOnlineMeetingReference]...';


GO
CREATE TABLE [sEMeeting].[tOnlineMeetingReference] (
    [AutoId]          BIGINT          IDENTITY (1, 1) NOT NULL,
    [OnlineMeetingId] BIGINT          NOT NULL,
    [ReferencePath]   NVARCHAR (1000) NOT NULL,
    CONSTRAINT [PK_tOnlineMeetingReference] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sEMeeting].[tOnlineMeetingSettings]...';


GO
CREATE TABLE [sEMeeting].[tOnlineMeetingSettings] (
    [OnlineMeetingId]            BIGINT         NOT NULL,
    [IsOnParticipantVideo]       BIT            NULL,
    [IsOnParticipantAudio]       BIT            NULL,
    [IsOnHostVideo]              BIT            NULL,
    [IsOnHostAudio]              BIT            NULL,
    [IsOnParticipantScreenShare] BIT            NULL,
    [IsOnHostscreenShare]        BIT            NULL,
    [AccountEmailId]             NVARCHAR (200) NULL,
    [AccountPassword]            NVARCHAR (200) NULL,
    [APIKey]                     NVARCHAR (100) NULL,
    [APISecret]                  NVARCHAR (100) NULL,
    [WebAPIKey]                  NVARCHAR (100) NULL,
    [WebAPISecret]               NVARCHAR (100) NULL,
    [MeetingProviderId]          SMALLINT       NULL,
    [JWTToken]                   NVARCHAR (MAX) NULL,
    [OAuthAccountId]             NVARCHAR (MAX) NULL,
    [OAuthClientId]              NVARCHAR (MAX) NULL,
    [OAuthClientSecret]          NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_tOnlineMeetingSettings] PRIMARY KEY CLUSTERED ([OnlineMeetingId] ASC)
);


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


GO
CREATE TABLE [sEMeeting].[tMeetingTypeMaster] (
    [AutoId]          SMALLINT      IDENTITY (1, 1) NOT NULL,
    [OrgGroupId]      SMALLINT      NOT NULL,
    [Name]            NVARCHAR (50) NOT NULL,
    [IsObsolete]      BIT           NULL,
    [CreatedUserId]   BIGINT        NOT NULL,
    [CreatedDateTime] DATETIME      NOT NULL,
    [UpdatedUserId]   BIGINT        NULL,
    [UpdatedDateTime] DATETIME      NULL,
    CONSTRAINT [PK_tMeetingTypeMaster] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


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


GO
CREATE TABLE [sEMeeting].[tOnlineMeeting] (
    [Id]                 BIGINT          NOT NULL,
    [OrgGroupId]         SMALLINT        NOT NULL,
    [MeetingTypeId]      SMALLINT        NOT NULL,
    [StartDate]          DATE            NOT NULL,
    [StartTime]          TIME (7)        NOT NULL,
    [EndDate]            DATE            NOT NULL,
    [EndTime]            TIME (7)        NOT NULL,
    [HostEmployeeId]     BIGINT          NOT NULL,
    [Title]              NVARCHAR (200)  NULL,
    [Description]        NVARCHAR (1000) NULL,
    [IsDisplayMeetingId] BIT             NOT NULL,
    [MeetingId]          NVARCHAR (100)  NULL,
    [MeetingPassword]    NVARCHAR (100)  NULL,
    [IsReference]        BIT             NULL,
    [IsResource]         BIT             NULL,
    [IsCompleted]        SMALLINT        NULL,
    [IsMeetingStarted]   BIT             NULL,
    [MeetingAccountId]   INT             NULL,
    [IsMeetingCreated]   BIT             NULL,
    [IsObsolete]         BIT             NULL,
    [CreatedUserId]      BIGINT          NOT NULL,
    [CreatedDateTime]    DATETIME        NOT NULL,
    [UpdatedUserId]      BIGINT          NULL,
    [UpdatedDateTime]    DATETIME        NULL,
    CONSTRAINT [PK_tOnlineMeeting] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sEMeeting].[tOnlineMeetingScope] (
    [AutoId]            BIGINT   IDENTITY (1, 1) NOT NULL,
    [OnlineMeetingId]   BIGINT   NOT NULL,
    [ScopeSourceTypeId] SMALLINT NOT NULL,
    [ScopeSourceId]     BIGINT   NOT NULL,
    [IsObsolete]        BIT      NULL,
    [CreatedUserId]     BIGINT   NOT NULL,
    [CreatedDateTime]   DATETIME NOT NULL,
    [UpdatedUserId]     BIGINT   NULL,
    [UpdatedDateTime]   DATETIME NULL,
    CONSTRAINT [PK_tOnlineMeetingScope] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sEMeeting].[tOnlineMeetingResource]...';


GO
CREATE TABLE [sEMeeting].[tOnlineMeetingResource] (
    [AutoId]          BIGINT          IDENTITY (1, 1) NOT NULL,
    [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,
    CONSTRAINT [PK_tOnlineMeetingResource] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tQualityCheckDetail] (
    [Id]                        BIGINT          NOT NULL,
    [OrgGroupId]                SMALLINT        NOT NULL,
    [QualityCheckId]            BIGINT          NOT NULL,
    [GoodsReceivedNoteDetailId] BIGINT          NULL,
    [UnitTypeId]                BIGINT          NOT NULL,
    [CategoryId]                BIGINT          NOT NULL,
    [SubCategoryId]             BIGINT          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) NULL,
    [ReasonForRejection]        NVARCHAR (300)  NULL,
    [CreatedUserId]             BIGINT          NULL,
    [CreatedDateTime]           DATETIME        NOT NULL,
    [UpdatedUserId]             BIGINT          NULL,
    [UpdatedDateTime]           DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tQualityCheckDetails] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tGoodsReceivedNote] (
    [Id]                 BIGINT          NOT NULL,
    [OrgGroupId]         SMALLINT        NOT NULL,
    [LocationId]         INT             NOT NULL,
    [IsObsolete]         BIT             NULL,
    [PurchaseRequestId]  BIGINT          NOT NULL,
    [PurchaseOrderId]    BIGINT          NOT NULL,
    [DepartmentBranchId] INT             NOT NULL,
    [VendorId]           INT             NOT NULL,
    [RequestedBy]        NVARCHAR (100)  NOT NULL,
    [BillToAddress]      NVARCHAR (1000) NOT NULL,
    [GRNNumber]          NVARCHAR (20)   NOT NULL,
    [StatusId]           SMALLINT        NOT NULL,
    [PODueDate]          DATETIME        NOT NULL,
    [CreatedUserId]      BIGINT          NULL,
    [CreatedDateTime]    DATETIME        NOT NULL,
    [UpdatedUserId]      BIGINT          NULL,
    [UpdatedDateTime]    DATETIME        NULL,
    [DeletedDateTime]    DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tGoodsReceivedNote] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tPurchaseOrder] (
    [Id]                BIGINT          NOT NULL,
    [OrgGroupId]        SMALLINT        NOT NULL,
    [LocationId]        INT             NOT NULL,
    [IsObsolete]        BIT             NULL,
    [PurchaseRequestId] BIGINT          NOT NULL,
    [RequestedBy]       NVARCHAR (100)  NOT NULL,
    [PODate]            DATETIME        NOT NULL,
    [RefNumber]         NVARCHAR (20)   NOT NULL,
    [StatusId]          SMALLINT        NOT NULL,
    [VendorId]          INT             NOT NULL,
    [BillToAddress]     NVARCHAR (1000) NOT NULL,
    [ShipToAddress]     NVARCHAR (1000) NOT NULL,
    [RequiredBy]        DATETIME        NOT NULL,
    [CreatedUserId]     BIGINT          NULL,
    [CreatedDateTime]   DATETIME        NOT NULL,
    [UpdatedUserId]     BIGINT          NULL,
    [UpdatedDateTime]   DATETIME        NULL,
    [DeletedDateTime]   DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tPurchaseOrder] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tPurchaseRequest] (
    [Id]              BIGINT         NOT NULL,
    [OrgGroupId]      SMALLINT       NOT NULL,
    [BranchId]        INT            NULL,
    [LocationId]      INT            NOT NULL,
    [IsObsolete]      BIT            NULL,
    [Number]          NVARCHAR (20)  NOT NULL,
    [RequestDate]     DATETIME       NULL,
    [ResourceId]      BIGINT         NULL,
    [RequestedBy]     NVARCHAR (100) NOT NULL,
    [StatusId]        SMALLINT       NULL,
    [VendorId]        INT            NULL,
    [RequiredBy]      DATETIME       NULL,
    [CreatedUserId]   BIGINT         NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL,
    [DeletedDateTime] DATETIME       NULL,
    CONSTRAINT [PK_sPurchase]].[tPurchaseRequest] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tQuotationRequest] (
    [Id]                BIGINT         NOT NULL,
    [OrgGroupId]        SMALLINT       NOT NULL,
    [BranchId]          INT            NULL,
    [LocationId]        INT            NOT NULL,
    [PurchaseRequestId] BIGINT         NOT NULL,
    [IsObsolete]        BIT            NULL,
    [Number]            NVARCHAR (20)  NOT NULL,
    [Name]              NVARCHAR (100) NULL,
    [RFQDate]           DATETIME       NOT NULL,
    [Description]       NVARCHAR (300) NULL,
    [StartDate]         DATETIME       NULL,
    [EndDate]           DATETIME       NULL,
    [BidOpen]           NVARCHAR (50)  NULL,
    [BidClose]          NVARCHAR (50)  NULL,
    [PersonContact]     BIGINT         NULL,
    [Email]             NVARCHAR (50)  NULL,
    [SendToVendor]      BIT            NULL,
    [StatusId]          SMALLINT       NOT NULL,
    [VendorId]          INT            NULL,
    [CreatedUserId]     BIGINT         NOT NULL,
    [CreatedDateTime]   DATETIME       NULL,
    [UpdatedUserId]     BIGINT         NULL,
    [UpdatedDateTime]   DATETIME       NULL,
    [DeletedDateTime]   DATETIME       NULL,
    CONSTRAINT [PK_sPurchase]].[tQuotationRequest] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tQualityCheck] (
    [Id]                  BIGINT         NOT NULL,
    [OrgGroupId]          SMALLINT       NOT NULL,
    [LocationId]          INT            NOT NULL,
    [IsObsolete]          BIT            NULL,
    [GoodsReceivedNoteId] BIGINT         NULL,
    [PurchaseOrderId]     BIGINT         NULL,
    [RequestedBy]         NVARCHAR (100) NOT NULL,
    [QCNumber]            NVARCHAR (20)  NOT NULL,
    [StatusId]            SMALLINT       NOT NULL,
    [CreatedUserId]       BIGINT         NULL,
    [CreatedDateTime]     DATETIME       NOT NULL,
    [UpdatedUserId]       BIGINT         NULL,
    [UpdatedDateTime]     DATETIME       NULL,
    [DeletedDateTime]     DATETIME       NULL,
    CONSTRAINT [PK_sPurchase]].[tQualityCheck] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tInvoiceGenerate] (
    [Id]                  BIGINT          NOT NULL,
    [OrgGroupId]          SMALLINT        NOT NULL,
    [LocationId]          INT             NOT NULL,
    [IsObsolete]          BIT             NULL,
    [InvoiceGenerateId]   BIGINT          NOT NULL,
    [GoodsReceivedNoteID] BIGINT          NOT NULL,
    [VendorId]            INT             NOT NULL,
    [INVNumber]           NVARCHAR (20)   NOT NULL,
    [RequestedBy]         NVARCHAR (100)  NOT NULL,
    [StatusId]            SMALLINT        NOT NULL,
    [InvoiceDate]         DATETIME        NOT NULL,
    [InvoiceDueDate]      DATETIME        NOT NULL,
    [BillToAddress]       NVARCHAR (1000) NOT NULL,
    [ShipToAddress]       NVARCHAR (1000) NOT NULL,
    [Remarks]             NVARCHAR (500)  NOT NULL,
    [CreatedUserId]       BIGINT          NULL,
    [CreatedDateTime]     DATETIME        NOT NULL,
    [UpdatedUserId]       BIGINT          NULL,
    [UpdatedDateTime]     DATETIME        NULL,
    [DeletedDateTime]     DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tInvoiceGenerate] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tInvoiceGenerateDetail] (
    [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,
    [ReasonForRejection]        NVARCHAR (300)  NULL,
    [UnitPrice]                 DECIMAL (12, 2) NOT NULL,
    [Remark]                    NVARCHAR (300)  NULL,
    [CreatedUserId]             BIGINT          NULL,
    [CreatedDateTime]           DATETIME        NOT NULL,
    [UpdatedUserId]             BIGINT          NULL,
    [UpdatedDateTime]           DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tInvoiceGenerateDetails] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tSalesReturn] (
    [Id]                  BIGINT         NOT NULL,
    [OrgGroupId]          SMALLINT       NOT NULL,
    [LocationId]          INT            NOT NULL,
    [IsObsolete]          BIT            NULL,
    [GoodsReceivedNoteId] BIGINT         NULL,
    [PurchaseOrderId]     BIGINT         NULL,
    [RequestedBy]         NVARCHAR (100) NOT NULL,
    [SRNumber]            NVARCHAR (20)  NOT NULL,
    [StatusId]            SMALLINT       NOT NULL,
    [CreatedUserId]       BIGINT         NULL,
    [CreatedDateTime]     DATETIME       NOT NULL,
    [UpdatedUserId]       BIGINT         NULL,
    [UpdatedDateTime]     DATETIME       NULL,
    [DeletedDateTime]     DATETIME       NULL,
    CONSTRAINT [PK_sPurchase]].[tSalesReturn] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tPurchaseLog] (
    [Id]              BIGINT             IDENTITY (1, 1) NOT NULL,
    [Message]         NVARCHAR (MAX)     NULL,
    [MessageTemplate] NVARCHAR (MAX)     NULL,
    [Level]           NVARCHAR (MAX)     NULL,
    [TimeStamp]       DATETIMEOFFSET (7) NOT NULL,
    [Exception]       NVARCHAR (MAX)     NULL,
    [Properties]      NVARCHAR (MAX)     NULL,
    CONSTRAINT [PK_PurchaseLog] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tSalesReturnDetail] (
    [Id]                        BIGINT          NOT NULL,
    [OrgGroupId]                SMALLINT        NOT NULL,
    [SalesReturnId]             BIGINT          NOT NULL,
    [GoodsReceivedNoteDetailId] BIGINT          NULL,
    [UnitTypeId]                BIGINT          NOT NULL,
    [CategoryId]                BIGINT          NOT NULL,
    [SubCategoryId]             BIGINT          NULL,
    [StockItemId]               BIGINT          NOT NULL,
    [POQty]                     DECIMAL (12, 2) NOT NULL,
    [ReceivedQty]               DECIMAL (12, 2) NOT NULL,
    [RejectedQty]               DECIMAL (12, 2) NULL,
    [CreditNoteIssueDate]       DATETIME        NULL,
    [ReasonForRejection]        NVARCHAR (300)  NULL,
    [CreatedUserId]             BIGINT          NULL,
    [CreatedDateTime]           DATETIME        NOT NULL,
    [UpdatedUserId]             BIGINT          NULL,
    [UpdatedDateTime]           DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tSalesReturnDetails] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tQuotationRequestDetail] (
    [Id]                      BIGINT          NOT NULL,
    [OrgGroupId]              SMALLINT        NOT NULL,
    [QuotationRequestId]      BIGINT          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,
    [CreatedUserId]           BIGINT          NOT NULL,
    [CreatedDateTime]         DATETIME        NULL,
    [UpdatedUserId]           BIGINT          NULL,
    [UpdatedDateTime]         DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tQuotationRequestDetails] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tPurchaseRequestDetail] (
    [Id]                BIGINT          NOT NULL,
    [OrgGroupId]        SMALLINT        NOT NULL,
    [PurchaseRequestId] BIGINT          NOT NULL,
    [StockItemId]       BIGINT          NOT NULL,
    [RequestedQty]      DECIMAL (12, 2) NOT NULL,
    [Remark]            NVARCHAR (300)  NULL,
    [CreatedUserId]     BIGINT          NULL,
    [CreatedDateTime]   DATETIME        NULL,
    [UpdatedUserId]     BIGINT          NULL,
    [UpdatedDateTime]   DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tPurchaseRequestDetails] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tPurchaseOrderDetail] (
    [Id]                      BIGINT          NOT NULL,
    [OrgGroupId]              SMALLINT        NOT NULL,
    [PurchaseOrderId]         BIGINT          NOT NULL,
    [PurchaseRequestDetailId] BIGINT          NOT NULL,
    [StockItemId]             BIGINT          NOT NULL,
    [TotalQty]                DECIMAL (12, 2) NOT NULL,
    [Remark]                  NVARCHAR (300)  NULL,
    [CreatedUserId]           BIGINT          NULL,
    [CreatedDateTime]         DATETIME        NOT NULL,
    [UpdatedUserId]           BIGINT          NULL,
    [UpdatedDateTime]         DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tPurchaseOrderDetails] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sPurchase].[tGoodsReceivedNoteDetail] (
    [Id]                      BIGINT          NOT NULL,
    [OrgGroupId]              SMALLINT        NOT NULL,
    [GoodsReceivedNoteId]     BIGINT          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,
    [CreatedUserId]           BIGINT          NULL,
    [CreatedDateTime]         DATETIME        NOT NULL,
    [UpdatedUserId]           BIGINT          NULL,
    [UpdatedDateTime]         DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tGoodsReceivedNoteDetails] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfApprovalActionLog]...';


GO
CREATE TABLE [sWf].[tWfApprovalActionLog] (
    [AutoId]             INT             IDENTITY (1, 1) NOT NULL,
    [WfApprovalActionId] BIGINT          NOT NULL,
    [ActionByEmployeeId] BIGINT          NOT NULL,
    [StatusId]           SMALLINT        NOT NULL,
    [IsSequancial]       BIT             NULL,
    [ActionRemark]       NVARCHAR (1000) NULL,
    [CreatedUserId]      BIGINT          NOT NULL,
    [CreatedDateTime]    DATETIME        NOT NULL,
    CONSTRAINT [PK_tWfApprovalActionLog] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfHierarchyLevel]...';


GO
CREATE TABLE [sWf].[tWfHierarchyLevel] (
    [AutoId]             BIGINT         IDENTITY (1, 1) NOT NULL,
    [WfApprovalActionId] BIGINT         NOT NULL,
    [StatusId]           SMALLINT       NOT NULL,
    [Remark]             NVARCHAR (500) NULL,
    [ActionByEmployeeId] BIGINT         NOT NULL,
    [ActionDatetime]     DATETIME       NULL,
    CONSTRAINT [PK_tWfHierarchyLevel] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfTypeMaster]...';


GO
CREATE TABLE [sWf].[tWfTypeMaster] (
    [Id]         SMALLINT       NOT NULL,
    [Code]       NVARCHAR (100) NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL,
    CONSTRAINT [PK_tWfTypeMaster_1] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfStatusMaster]...';


GO
CREATE TABLE [sWf].[tWfStatusMaster] (
    [Id]         SMALLINT       NOT NULL,
    [Code]       NVARCHAR (100) NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL,
    CONSTRAINT [PK_tWfStatusMaster_1] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfFunctionalityMaster]...';


GO
CREATE TABLE [sWf].[tWfFunctionalityMaster] (
    [Id]         SMALLINT       NOT NULL,
    [Code]       NVARCHAR (100) NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL,
    CONSTRAINT [PK_tWfFunctionalityMaster_1] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfApprovalAction]...';


GO
CREATE TABLE [sWf].[tWfApprovalAction] (
    [Id]                BIGINT         NOT NULL,
    [OrgGroupId]        SMALLINT       NOT NULL,
    [ActionEmployeeId]  BIGINT         NOT NULL,
    [ActionStatusId]    TINYINT        NOT NULL,
    [ActionRemark]      NVARCHAR (500) NOT NULL,
    [WfFunctionalityId] SMALLINT       NOT NULL,
    [DocSourceTypeId]   SMALLINT       NOT NULL,
    [DocSourceId]       BIGINT         NOT NULL,
    [CreatedUserId]     BIGINT         NULL,
    [CreatedDateTime]   DATETIME       NOT NULL,
    [UpdatedUserId]     BIGINT         NULL,
    [UpdatedDateTime]   DATETIME       NULL,
    CONSTRAINT [PK_tWfApprovalAction] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfApprovingAuthority]...';


GO
CREATE TABLE [sWf].[tWfApprovingAuthority] (
    [AutoId]                INT      IDENTITY (1, 1) NOT NULL,
    [AuthoritySourceTypeId] SMALLINT NOT NULL,
    [AuthoritySourceId]     BIGINT   NOT NULL,
    [OrgId]                 SMALLINT NOT NULL,
    [WfFunctionalityId]     SMALLINT NULL,
    CONSTRAINT [PK_tWfApprovingAuthority_1] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfSetup]...';


GO
CREATE TABLE [sWf].[tWfSetup] (
    [AutoId]            SMALLINT IDENTITY (1, 1) NOT NULL,
    [WfTypeMasterId]    SMALLINT NOT NULL,
    [WfLevel]           SMALLINT NOT NULL,
    [OrgGroupId]        SMALLINT NOT NULL,
    [WfFunctionalityId] SMALLINT NOT NULL,
    [IsObsolete]        BIT      NOT NULL,
    CONSTRAINT [PK_tWfSetup_1] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sBiometric].[tCloudTransactionDataHistory]...';


GO
CREATE TABLE [sBiometric].[tCloudTransactionDataHistory] (
    [AutoId]          BIGINT        NOT NULL,
    [SourceId]        BIGINT        NOT NULL,
    [In_Out_Time]     DATETIME      NOT NULL,
    [ShiftCode]       INT           NOT NULL,
    [Attn_Dt]         DATE          NOT NULL,
    [Mode]            NVARCHAR (10) NOT NULL,
    [CreatedDateTime] DATETIME      NOT NULL,
    [DeviceIP]        NVARCHAR (20) NOT NULL,
    [EntryMode]       TINYINT       NOT NULL,
    [PunchId]         NVARCHAR (50) NULL,
    [TransactionId]   BIGINT        NOT NULL,
    [SourceTypeId]    SMALLINT      NULL,
    [IsProcessed]     BIT           NULL
);


GO
PRINT N'Creating Table [sBiometric].[tCloudTransactionRawDataHistory]...';


GO
CREATE TABLE [sBiometric].[tCloudTransactionRawDataHistory] (
    [TransactionId]       BIGINT        NOT NULL,
    [PunchId]             NVARCHAR (50) NULL,
    [TransactionDateTime] DATETIME      NOT NULL,
    [DeviceIP]            NVARCHAR (20) NOT NULL,
    [Mode]                NVARCHAR (10) NOT NULL,
    [CreatedDateTime]     DATETIME      NOT NULL
);


GO
PRINT N'Creating Table [sCommunication].[tCircularConsent]...';


GO
CREATE TABLE [sCommunication].[tCircularConsent] (
    [Id]                  BIGINT         IDENTITY (1, 1) NOT NULL,
    [CircularId]          BIGINT         NOT NULL,
    [QuestionDescription] NVARCHAR (MAX) NOT NULL,
    [AnsFieldTypeId]      INT            NOT NULL,
    [AnsFieldList]        NVARCHAR (MAX) NOT NULL,
    CONSTRAINT [PK_tCircularConsentQuestion] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sCommunication].[tCircularConsentResult]...';


GO
CREATE TABLE [sCommunication].[tCircularConsentResult] (
    [Id]                 BIGINT         IDENTITY (1, 1) NOT NULL,
    [SourceId]           BIGINT         NOT NULL,
    [CircularConsentId]  BIGINT         NOT NULL,
    [CircularConsentAns] NVARCHAR (MAX) NOT NULL,
    CONSTRAINT [PK_tCircularConsentResult] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sFee].[tTempReceipt]...';


GO
CREATE TABLE [sFee].[tTempReceipt] (
    [Id]                   BIGINT          NOT NULL,
    [SourceTypeId]         SMALLINT        NULL,
    [SourceId]             BIGINT          NULL,
    [ReceiptNumber]        INT             NOT NULL,
    [ReceiptDate]          DATE            NOT NULL,
    [ReceiptAmount]        DECIMAL (12, 2) NULL,
    [PayTypeId]            TINYINT         NOT NULL,
    [ChequeNo]             NVARCHAR (40)   NULL,
    [BankName]             NVARCHAR (200)  NULL,
    [ReceiptBookId]        INT             NOT NULL,
    [Remark]               NVARCHAR (200)  NULL,
    [IsObsolete]           BIT             NOT NULL,
    [BatchId]              INT             NULL,
    [OrgGroupBatchId]      INT             NULL,
    [CreatedUserId]        BIGINT          NOT NULL,
    [CreatedDateTime]      DATETIME        NOT NULL,
    [TotalReceiptAmount]   DECIMAL (12, 2) NULL,
    [DiscountAmount]       DECIMAL (12, 2) NULL,
    [IsChequeCleared]      BIT             NULL,
    [ChequeClearDate]      DATE            NULL,
    [ChequeDate]           DATE            NULL,
    [FeeInvoiceId]         BIGINT          NULL,
    [CollectionGroupId]    INT             NULL,
    [AmountAfterDiscount]  DECIMAL (12, 2) NULL,
    [CGSTPercentage]       DECIMAL (5, 2)  NULL,
    [SGSTPercentage]       DECIMAL (5, 2)  NULL,
    [CGSTAmount]           DECIMAL (12, 2) NULL,
    [SGSTAmount]           DECIMAL (12, 2) NULL,
    [DepositedLedgerId]    INT             NULL,
    [PaymentTransactionId] BIGINT          NULL,
    [ReceiptPrintGroupId]  NVARCHAR (100)  NULL,
    [CancelStatusId]       SMALLINT        NULL,
    [CancelStatusRemark]   NVARCHAR (500)  NULL,
    [IsDiscountCoupon]     BIT             NULL,
    [FirmReceiptBookId]    INT             NULL
);


GO
PRINT N'Creating Index [sBiometric].[tCloudTransactionData].[CloudTransactionData_Autoid_TransactionId]...';


GO
CREATE NONCLUSTERED INDEX [CloudTransactionData_Autoid_TransactionId]
    ON [sBiometric].[tCloudTransactionData]([AutoId] ASC, [TransactionId] ASC);


GO
PRINT N'Creating Default Constraint [sEMeeting].[DF_tMeetingTypeMaster_IsObsolete]...';


GO
ALTER TABLE [sEMeeting].[tMeetingTypeMaster]
    ADD CONSTRAINT [DF_tMeetingTypeMaster_IsObsolete] DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint [sEMeeting].[DF_tOnlineMeeting_IsObsolete]...';


GO
ALTER TABLE [sEMeeting].[tOnlineMeeting]
    ADD CONSTRAINT [DF_tOnlineMeeting_IsObsolete] DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint [sEMeeting].[DF_tOnlineMeetingScope_IsObsolete]...';


GO
ALTER TABLE [sEMeeting].[tOnlineMeetingScope]
    ADD CONSTRAINT [DF_tOnlineMeetingScope_IsObsolete] DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint [sEMeeting].[DF_tOnlineMeetingResource_IsObsolete]...';


GO
ALTER TABLE [sEMeeting].[tOnlineMeetingResource]
    ADD CONSTRAINT [DF_tOnlineMeetingResource_IsObsolete] DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sPurchase].[tGoodsReceivedNote]...';


GO
ALTER TABLE [sPurchase].[tGoodsReceivedNote]
    ADD DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sPurchase].[tPurchaseOrder]...';


GO
ALTER TABLE [sPurchase].[tPurchaseOrder]
    ADD DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sPurchase].[tPurchaseRequest]...';


GO
ALTER TABLE [sPurchase].[tPurchaseRequest]
    ADD DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sPurchase].[tQuotationRequest]...';


GO
ALTER TABLE [sPurchase].[tQuotationRequest]
    ADD DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sPurchase].[tQualityCheck]...';


GO
ALTER TABLE [sPurchase].[tQualityCheck]
    ADD DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sPurchase].[tInvoiceGenerate]...';


GO
ALTER TABLE [sPurchase].[tInvoiceGenerate]
    ADD DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sPurchase].[tSalesReturn]...';


GO
ALTER TABLE [sPurchase].[tSalesReturn]
    ADD DEFAULT ((0)) FOR [IsObsolete];


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


GO
ALTER TABLE [sWf].[tWfApprovalActionLog]
    ADD DEFAULT ((0)) FOR [IsSequancial];




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


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



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


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



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



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



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




GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[vStudentAllDetail]';




GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[vStudentColumnName]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[vStudentCustomSearch]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[vStudentDetails]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[vStudentVerification]';



GO

CREATE FUNCTION [sAssessment].[fSubjectWiseGradeGet](@rAcademicId bigint,@rExamId int,@rActivityId int,@rClassSubjectId int,@rBatchId int,@rClassId int)
RETURNS nvarchar(100) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lGrade nvarchar(100)=''
  
	DECLARE @lMarks decimal(5,2), @lScore decimal(5,2),@lGradeSetId int, @lTotalActivityCount int , @lSubjectMaximum decimal(5,2)

	SELECT @lMarks = SUM(AIS.Marks) from sAssessment.tCCESubjectSubActivityExamScore AIS
		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id
		INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId
		WHERE AIS.AcademicId = @rAcademicId AND AIS.ExamId = @rExamId AND SAM.Id = @rActivityId

	SELECT @lTotalActivityCount = COUNT(1) from sAssessment.tCCESubjectSubActivityExamScore AIS
		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id
		INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId
		WHERE AIS.AcademicId = @rAcademicId AND AIS.ExamId = @rExamId AND SAM.Id = @rActivityId

	SELECT @lSubjectMaximum = ED.Maximum from [sAssessment].[tExamDetail] ED
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		WHERE ED.ExamId = @rExamId AND ED.ClassSubjectId = @rClassSubjectId AND EM.BatchId = @rBatchId AND EM.ClassId = @rClassId

	SELECT @lGradeSetId = ED.GradeSetId from [sAssessment].[tExamDetail] ED
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		WHERE ExamId = @rExamId AND ClassSubjectId = @rClassSubjectId AND EM.BatchId = @rBatchId AND EM.ClassId = @rClassId
	
	SET @lScore = (@lMarks * 100) / (@lSubjectMaximum * @lTotalActivityCount)

	SELECT TOP 1 @lGrade = GradeCode
		FROM sAssessment.tGradeSetDetail
		WHERE MinimumScore <= @lScore AND GradesetId = @lGradeSetId
		ORDER BY MinimumScore DESC
	


	return  @lGrade
END
GO
PRINT N'Altering Procedure [sAlert].[pAlertQueueLogAdd]...';


GO
ALTER PROCEDURE [sAlert].[pAlertQueueLogAdd]
	@rId bigint = 0,
	@rMessageDate datetime = null,
	@rQueueMessage nvarchar(max) = '',
	@rEventId int = 0,
	@rAlertModeId tinyint = 0,
	@rOrgId smallint = 0,
	@rCreatedUserId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
		IF(@rId = 0)	
		BEGIN
			DECLARE @lNextNumber BIGINT  
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAlert.tAlertQueueLog', 0, 1, 1,@outNextNumber = @lNextNumber output

			INSERT INTO [sAlert].[tAlertQueueLog]
				([AutoId]
				,[MessageDate]
			    ,[QueueMessage]
			    ,[EventId]
			    ,[AlertModeId]
			    ,[OrgId]
			    ,[CreatedUserId]
			    ,[CreatedDateTime])
		   VALUES
				(@lNextNumber
				,@rMessageDate
			    ,@rQueueMessage
			    ,@rEventId
			    ,@rAlertModeId
			    ,@rOrgId
			    ,@rCreatedUserId
			    ,sCommon.fGetDate())

			SELECT @@IDENTITY AS Result
		END
		ELSE
		BEGIN
			UPDATE [sAlert].[tAlertQueueLog] SET [QueueMessage] = @rQueueMessage WHERE AutoId = @rId

			SELECT @rId AS Result
		END
	COMMIT TRANSACTION
    END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering Procedure [sCertificate].[pRptCharacterCertificateGet]...';


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

DECLARE @lConfigValue nvarchar(50)

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

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

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

	--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 
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			C.Id,
			C.AcademicId,
			SM.Code,
		--	SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
		   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			CM.DisplayTitle AS ClassOnly,
			BM.Title AS Batch,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			C.characterDate,
			C.Number,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgName,
			OM.StateName+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			SA.AdmissionDate,
			SF.FatherName,
			SF.MotherName,
			@lIDConfigValue AS ItemValue,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			A.Id,
			SA.LeftDate AS LCDate,
			C.Remark AS Remark,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(OM.PrincipalSignature,0x) AS PrincipalSignature,
			SM.FirstName,
			SM.LastName,
			SM.MiddleName,
			SM.SUId As SUID,
			DM.DisplayTitle AS DivisionOnly,
			@lIsShowPhoto AS IsShowPhoto,		--add for 27638 mantis start
			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.tCharacter C
			INNER JOIN sStudent.tAcademic A ON C.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId			--add for 27638 mantis
	WHERE  
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((C.Number=@rNumber) OR (@rNumber=''))
		AND ((C.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((C.Number <= @rToNo) OR (@rToNo=''))
		AND ((C.characterDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((C.characterDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--Group By C.AcademicId,C.Number,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
		--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,C.characterDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,OM.OrgLogo,OM.Title,
		--OM.StreetOne,OM.StreetThree,OM.StreetTwo,OM.PhoneNo
	END
GO
PRINT N'Altering Procedure [sCertificate].[pRptBonafiedCertificateGet]...';


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

DECLARE @lIsShowPhoto bit = 0
DECLARE @lIsOnPrePrinted bit = 0
DECLARE @lIsDisplayReligion bit=0
DECLARE @lIsDisplayImageHeader bit=0

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


	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 177 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	
	Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	
	
	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			B.Id,
			B.Number,
			B.AcademicId,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			B.BonafideDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			--OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			--OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			ATM.Title AS AffiliationType,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			@lIsShowPhoto AS IsShowPhoto,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			B.Remark AS ReceiptNo,
			SF.FatherName,
			SA.AdmissionDate,
			DP.Title AS DepartmentName,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4,
			REPLICATE(',',OM.LetterHeadMargin)    AS LetterHeadMargin,
			ISNULL(B.BonafiedReason,'') AS BonafiedReason,
			CT.Title AS Category,
			SF.MotherName,
			C.PermanentStreetOne,
			C.PermanentStreetTwo,
			C.PermanentStreetThree,
			C.PermanentCountry,
			C.PermanentState,
			C.PermanentCity,
			C.PermanentZipCode,
			C.PermanentContactNo,
			C.PresentStreetOne,
			C.PresentStreetTwo,
			C.PresentStreetThree,
			C.PresentCountry,
			C.PresentState,
			C.PresentCity,
			C.PresentContactNo,
			C.PresentZipCode,
			SM.SUId,
			SO.AdhaarNumber,
			CM.DisplayTitle AS ClassName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			OM.PrincipalSignature,
			ISnull(AR.SourceId,0) AS StudentidForhostel,
			DM.DisplayTitle AS Divisionname,
			@lIDConfigValue AS ItemValue ,
			SM.RecordStatusId,
			SO.BirthState AS BirthState,
			CM1.Title AS AdmissionStandard,
			RRG.SchoolRemark1,
			RRG.SchoolRemark2,
			RRG.SchoolRemark3,
			SF.FatherAdhaarNumber AS FatherAadharNo,
			SF.MotherAdhaarNumber AS MotherAadharNo,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			--OI.CertificateHeaderA4,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			SM.Id AS StudentId,
			(CASE WHEN RRG.SchoolRequiredSignature IS NULL THEN NULL ELSE RRG.SchoolRequiredSignature END) AS SchoolRequiredSignature ,
			SO.UIDNumber,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			BM.FromDate AS BatchFromDate,
			BM.ToDate AS BatchToDate ,

			ISNULL(U.DisplayTitle,'') AS UserName ,
		
		    ISNULL(EM.FirstName,'') +' '+ISNULL(EM.LastName,'') AS PrincipalName,
			ISNULL(CM.ClassNameInWord,'') AS ClassNameInWord,
			CM2.Title AS LeftStandard,
			CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,			--add for 27638 mantis
			ISNULL(SI.QRCode,'') AS QRCode							--add for 27638 mantis
	FROM 
			sCertificate.tBonafide B
			
			INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id = SA.AdmissionStandardId
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN SHostel.tAssignRoom Ar On Ar.SourceId=A.StudentId AND Ar.OrgGroupBatchId=@rOrgGroupBatchId 
			LEFT JOIN sCommon.tReportRemarkGroupOrg RRG ON RRG.OrgId = OM.Id AND ReportRemarkGroupId=6
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId 
			LEFT JOIN sSecurity.tUser U	ON U.Id=B.CreatedUserId

			Left join sHrm.tEmployeeMaster EM on EM.Id = OM.EmployeeId
			LEFT JOIN sSetup.tClassMaster CM2 ON CM2.Id = SA.LeftStandardId
			--INNER JOIN sSetup.tTermMaster TM ON  TM.ID=
	WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			--AND ((B.BonafideDate=@rBonafiedDate) OR (ISNULL(@rBonafiedDate,'')=''))
			AND ((B.Number=@rNumber) OR (@rNumber=''))
			AND ((B.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((B.Number <= @rToNo) OR (@rToNo=''))
			AND ((B.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((B.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--Group By B.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
			--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,B.BonafideDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,
			--OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering 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

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

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


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

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

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


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

--IF(@lOrgId IS NULL)
--BEGIN
--SELECT @lSchoolRemark1=DefaultRemark1,@lSchoolRemark2=DefaultRemark2,@lSchoolRemark3=DefaultRemark3,@lSchoolRequiredSignature=DefaultRequiredSignature FROM sCommon.tReportRemarkGroupMaster WHERE Id=3
--END


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

	--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
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--MR.PresentCount AS PresentDays ,
			--MR.TotalCount AS TotalDays ,
			L.Id,
			--(SELECT SUM(MR.PresentCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS PresentDaysSum ,
			--(SELECT SUM(MR.TotalCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS TotalDaysSum ,
			SM.Code,
			L.AcademicId,
			SM.FirstName,SM.MiddleName,SM.LastName,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			--0 As CastCategoryId,
			--ISNULL(SO.CastCategoryId,0) As CastCategoryId,
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			SA.PreviousSchool,
			SA.AdmissionDate,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			SO.GenderId,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(SC.PresentState,'') AS CityState,
			CM.DisplayTitle AS AdmissionStandard,
			CMS.DisplayTitle AS CurrentStandard,
			CMS.Title AS CurrentStandardTitle,
			--'' AS CurrentStandardInWords,
			SM.StatusId,
			L.LastExamName AS Result,
			L.LastExamResult AS FailOrPass,
			L.SubjectStudied AS SubjectNAme,
			L.RepeatDetail as PromotedorNot,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			--'' AS PromotedorNot,
			L.PromoteToClass  AS PromotedToClass,
			L.FeeDetail AS LastFeesPaid,
			L.FeeConcessionDetail AS AnyConcession,
			L.NCCScoutDetail  AS NCCScoutDetail,
			L.ExtraCurricularActivities AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			AD.PresentDaysAnnual AS PresentDaysSum,
			AD.TotalDaysAnnual AS TotalDaysSum,
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(L.ToCollege,'') AS ToCollege ,
			ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
			ISNULL(OM.University,'')AS University,
			@lSchoolRemark1 AS SchoolRemark1 ,
			@lSchoolRemark2 AS SchoolRemark2 ,
			@lSchoolRemark3 AS SchoolRemark3 ,
			@lSchoolRequiredSignature AS SchoolRequiredSignature,
			ISNULL(CMS.ClassNameInWord,'')AS CurrentStandardInWords,
			SO.MotherTongue,
			SO.AdhaarNumber,
			vSA.SUId,
			CASE WHEN isnull(BM.FromDate,'')>Isnull(SA.AdmissionDate,'') THEN BM.FromDate ELSE SA.AdmissionDate END AS BatchDate,
			SO.BirthState,
			SO.BirthCountry,
			SD.BankAccountNumber,
			SO.UIDNumber,
			SD.BankName,
			SD.BankIFSCCode,
			SA.PreviousStandard 
			,L.TermsInInstitute,
			@lIDConfigValue AS ItemValue 
			,L.LCCopy
			,DM.InchargeEmployeeId AS ClassTeacher
			,vSA.BatchName AS BatchName,
			CSM.Title As CasteCategory,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SI.StudentPhoto,
			SA.AdmissionFormNumber,
			BM.FromDate as BatchStartDate,
			BM.ToDate as BatchEndDate,
			SO.UIDNumber,
			SC.PresentStreetOne AS Address1,
			SC.PresentStreetTwo AS Address2,
			SC.PresentStreetThree AS Address3,
			SC.PresentCity AS PresentCity,
			SC.PresentZipCode AS PresentZipCode,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			L.TotalDays,
			L.PresentDays,
			ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
		--sFinanceCommon.fNumberToWords(ISNULL(CM.ClassGroupId,0),'',OM.OrgGroupId) AS CurrentStandardInWords
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.PresentCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.PresentCount,0))
		--END AS Presentdays,
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.TotalCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.TotalCount,0))
		--END AS TotalCount
		@rUserName AS UserName,
		EI.EmployeeSign,
		EI1.EmployeeSign AS DivisionInchargeEmployeeSign,
		ISNULL(L.ProofOfDOB,'')AS ProofOfDOB,
		U.LoginTitle AS CreatedUserName,
		OM.PrincipalSignature,
		CM.ClassNameInWord AS AdmissionStandardInWord,
		LM.Title AS LanguageTitle,
		@lIsShowPhoto AS IsShowPhoto,		--add for 27638 mantis start
		CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
		ISNULL(SI.QRCode,'') AS QRCode		--add for 27638 mantis end
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			--INNER JOIN sStudent.tAcademic A ON L.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			INNER JOIN sSecurity.tUser U ON U.Id = L.CreatedUserId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			--LEFT JOIN  sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id 
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			--LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			--AND BM.OrgGroupBatchId=vSA.OrgGroupBatchId
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sSetup.tDivisionInchargeEmployee DIE ON vSA.DivisionId = DIE.DivisionId AND DIE.BatchId = vSA.BatchId
			AND DIE.Number = (SELECT MIN(Number) FROM sSetup.tDivisionInchargeEmployee WHERE  DIE.DivisionId = vSA.DivisionId AND DIE.BatchId = vSA.BatchId)
			LEFT JOIN sHrm.tEmployeeImages EI1 ON EI1.EmployeeId = DIE.EmployeeId
			INNER JOIN sSetup.tLanguageMaster LM ON LM.Id = OM.LanguageId
	WHERE 
				L.OrgId=@rOrgId
				AND	vSA.BatchId = @rBatchId 
				AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
				AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				--AND ((L.LCDate=@rLCDate) OR (ISNULL(@rLCDate,'')=''))
				--AND ((L.LeftDate=@rLeftDate) OR (ISNULL(@rLeftDate,'')=''))
				--AND ((L.LCCopy=@rLCCopy) OR (@rLCCopy=0))
				--AND ((L.LCBookNumber=@rLCBookNumber) OR (@rLCBookNumber=''))
				AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
				AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
				AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
				AND ((DM.ClassId=@rClassId) OR(@rClassId=0))
				--group by MR.PresentCount,MR.TotalCount, SubM.Title, SM.Code,L.AcademicId,SM.FirstName,SM.LastName,SM.MiddleName,SF.FatherName,SF.MotherName,NM.Title,
				--SO.CastCategoryId,RM.Title,so.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,SO.DateOfBirth,SO.BirthDateInWord,SA.PreviousSchool,
				--	SA.AdmissionDate,L.LeftDate,L.LCReason,L.LCProgress,L.LCConduct,L.LCRemark,L.LCDate,SO.GenderId,
				--	OM.CityName,OM.StateName,CM.DisplayTitle,CMS.DisplayTitle,SM.StatusId,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
END
GO
PRINT N'Altering Procedure [sCommon].[pOrganizationSetupRemove]...';


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

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


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

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

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

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

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

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

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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


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

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

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

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

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

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

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

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


DELETE FROM sAlumni.tStudentMapping WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tUserFeedback WHERE CAST(LEFT(UserId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeExpense WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId


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

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

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

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

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


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

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


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

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


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

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


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

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

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

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


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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

DELETE FROM sAdmission.tAdmissionCustomSearch WHERE OrgId = @rOrgId

DELETE FROM[sCommunication].[tTempQueryCategoryScope] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId


DELETE FROM [sStudent].[tOnlineRegistrationStudentAdmission] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentCommunication] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentCustomFieldData] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentDocument] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentFamily] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentImages] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentOther] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCollegeDetail] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationDisplayField]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaDocument]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaForm]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentMaster] WHERE OrgId = @rOrgId

DELETE FROM [sBiometric].[tShiftAllocationCloud] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sBiometric].[tCloudTransactionData] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM [sTransport].[tAssignRouteLog] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sAttendance].[tAttendanceFollowup] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId

DELETE FROM sAssessment.tAssessmentLabelSetup WHERE OrgId = @rOrgId
DELETE FROM [sAssessment].[tStudentExamRemark] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId
DELETE FROM [sBiometric].[tDeviceMasterCloud] WHERE OrgId = @rOrgId

DELETE FROM [sHrm].[tDigitalForm] WHERE OrgId = @rOrgId
DELETE FROM [sHrm].[tDigitalFormField] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sHrm].[tDigitalFormScope] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sHrm].[tDigitalFormEmployee] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sAdmission].[tAdmissionOptionalSubject] WHERE CAST(LEFT([AdmissionFormId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentOptionalSubject] WHERE CAST(LEFT([OnlineRegistrationStudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteria] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaOptionalSubject] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sAdmission].[tAdmissionCriteriaOptionalSubject] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId

DELETE FROM [sAlert].[tAlertTrackHistory] WHERE OrgId = @rOrgId
DELETE FROM [sActivity].[tEventInchargeAssign] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sLibrary].[tNewspaperLog] WHERE CAST(LEFT([NewspaperId], 4) AS int) = @rOrgId
DELETE FROM sSetup.tClassContentSetup WHERE CAST(LEFT([ClassId], 4) AS int) = @rOrgId

DELETE FROM[sHrm].[tCertificateJoining] WHERE [OrgId] = @rOrgId
DELETE FROM[sCommunication].[tTempMultiPhotoCategoryScope] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM[sStudent].[tDigitalFormStudentStatus] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId
DELETE FROM[sHrm].[tDigitalFormEmployeeStatus] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM[sHrm].[tLeaveHierarchyLevel] WHERE CAST(LEFT([LeaveId], 4) AS bigint) = @rOrgId

DELETE FROM [sAudit].[tChargeDeleted] WHERE [OrgId] = @rOrgId
DELETE FROM [sAudit].[tChargeDetailDelete] WHERE CAST(LEFT([ChargeReceiptId], 4) AS bigint) = @rOrgId

DELETE FROM sFee.tLateFeeRuleMaster WHERE OrgId = @rOrgId
DELETE FROM sAlert.tAlertQueueLog WHERE OrgId = @rOrgId



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

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


GO

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

BEGIN 


DECLARE @lMonthDays int

SELECT @lMonthDays = sCommon.fGetDaysInMonth(@rMonth,@rYear)
	SELECT 
			@lMonthDays AS MonthDays,
			Dept.Id AS DepartmentId,
			@rBuilder1 AS Builder1,
		    
		    (
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.AttendanceTypeId =1
			)
			AS BT,
			
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.AttendanceTypeId =1
			)
			AS GT,		
			
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			)
			 AS PB1,
			
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			)
			 AS PG1,
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)AS ABB1,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG1,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB1,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG1,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB1,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG1,
			
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId=1
			) AS PB2,
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId=1
			) AS PG2,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0 AND SR.AttendanceTypeId=1
			) AS ABB2,
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0 AND SR.AttendanceTypeId=1
			) AS ABG2,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB2,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG2,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB2,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS NAG2,
			
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND  SR.IsPresent=1 AND  SR.AttendanceTypeId=1
			) AS PB3,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId=1
			) AS PG3,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0 AND SR.AttendanceTypeId=1
			) AS ABB3,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0 AND SR.AttendanceTypeId=1
			) AS ABG3,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB3,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG3,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId			 
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB3,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId			 
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate =(convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS NAG3,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB4,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG4,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB4,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG4,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB4,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG4,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB4,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS NAG4,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB5,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG5,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB5,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG5,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB5,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG5,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB5,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG5,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB6,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG6,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB6,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG6,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB6,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG6,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB6,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG6,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB7,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG7,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB7,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG7,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB7,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG7,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB7,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG7,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB8,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG8,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB8,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG8,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB8,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG8,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB8,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG8,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB9,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG9,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1) AS ABB9,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG9,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB9,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id) AS LG9,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB9,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG9,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB10,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG10,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB10,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG10,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB10,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG10,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB10,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG10,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB11,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG11,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB11,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG11,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB11,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG11,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB11,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG11,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB12,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG12,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB12,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG12,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB12,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG12,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB12,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG12,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB13,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG13,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB13,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG13,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB13,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG13,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB13,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG13,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB14,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG14,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB14,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG14,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB14,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG14,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB14,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG14,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB15,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG15,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB15,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG15,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB15,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id) AS LG15,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB15,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS NAG15,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB16,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG16,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB16,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG16,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB16,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG16,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB16,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG16,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB17,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG17,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB17,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG17,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB17,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id) AS LG17,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB17,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG17,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB18,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG18,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB18,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG18,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB18,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG18,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB18,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG18,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB19,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG19,
			(	select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB19,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG19,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB19,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id) AS LG19,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB19,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG19,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB20,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG20,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB20,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG20,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB20,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG20,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB20,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG20,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB21,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG21,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB21,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG21,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB21,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG21,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB21,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG21,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB22,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG22,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB22,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG22,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB22,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG22,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB22,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG22,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB23,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG23,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB23,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG23,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB23,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG23,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB23,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG23,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB24,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG24,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB24,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG24,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB24,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG24,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB24,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG24,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB25,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG25,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB25,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG25,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB25,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG25,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB25,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG25,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB26,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG26,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB26,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG26,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB26,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG26,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB26,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG26,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB27,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG27,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB27,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG27,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB27,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG27,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB27,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG27,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB28,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG28,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB28,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG28,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB28,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG28,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB28,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG28,
			
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			)
			ELSE
			0
			END
			 AS PB29,
			 
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			)
			ELSE
			0
			END AS PG29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END AS ABB29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END AS ABG29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS LB29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END   AS LG29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS NAB29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			)ELSE
			0
			END  AS NAG29,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			)ELSE
			0
			END  AS PB30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END AS PG30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END  AS ABB30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END  AS ABG30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS LB30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS LG30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS NAB30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			)ELSE
			0
			END  AS NAG30,
			
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			)ELSE
			0
			END  AS PB31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END   AS PG31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END  AS ABB31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END AS ABG31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS LB31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END AS LG31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END AS NAB31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			)ELSE
			0
			END AS NAG31,
			--MS.AttendanceCount AS WorkingDays,
			MS.WorkingDays AS WorkingDays,
			Dept.Title AS DepartmentName,
			CM.Id AS ClassId,
			CM.Title AS ClassName,
			DM.Id AS DivId,
			DM.Title AS DivisionName,
			--@rStatus AS StatusCheck,
			--@rStatusClass AS StatusClass
			@rMonth AS StudentMonth,
			@rYear AS StudentYear
			
			FROM 
			
			
			sSetup.tDivisionMaster DM  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sAttendance.tMonthlySetup MS ON CM.Id=MS.ClassId		
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=MS.BatchId	
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId  
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
		
			
	WHERE 
		DM.OrgId=@rOrgId
		AND	MS.BatchId = @rBatchId 
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
		
		AND ((MS.ForMonth=@rMonth) OR(@rMonth =0)) 
		AND ((MS.ForYear=@rYear) OR (@rYear=0))
		AND DM.IsObsolete = 0
		--AND	BM.OrgGroupBatchId = @rOrgGroupBatchId 
	
	
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
			   
			   
		)
	VALUES
		(
			   @rStudentId,
			   @rPreviousSchool,
			   @rAdmissionStandardId,
			   @rAdmissionDate,
			   @rLeftStandardId,
			   @rLeftDate,
			   @rInactiveDate,
			   @rBatchId,
			   @rCreatedUserId,
			   sCommon.fGetDate(),
			   @rPreviousStandard,
			   @rPreviousLCNumber,
			   @rPreviousLCDate,
			   @rPreviousLCResult,
			   @rProofOfDOB
		)
		
		
		SELECT 1 AS Result             
	END	 
	 ELSE
	 BEGIN
		UPDATE sStudent.tStudentAdmission
	    SET
			  
			  AdmissionStandardId = @rAdmissionStandardId, 
			  AdmissionDate = @rAdmissionDate, 
			  LeftStandardId = @rLeftStandardId,
			  LeftDate = @rLeftDate, 
			  InactiveDate = @rInactiveDate, 
			  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].[pStudentAdmissionGet]...';


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

BEGIN 
	SELECT 
			  SA.StudentId,
			  SA.PreviousSchool,
			  ISNULL(SA.PreviousSchoolTypeId,0) AS PreviousSchoolTypeId,
			  ISNULL(SA.PreviousStudentId,0) AS PreviousStudentId,
			  ISNULL(SA.AdmissionFormId,0) AS AdmissionFormId,
			  SA.AdmissionFormNumber,
			  ISNULL(SA.AdmissionStandardId,0) AS AdmissionStandardId,
			  ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,
			  SA.AdmissionYear,
			  ISNULL(SA.LeftStandardId,0) AS LeftStandardId,
			  ISNULL(SA.LeftDate,'0001/01/01') AS LeftDate,
			  SA.LeftYear,
			  ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,
			  SA.InActiveReason,
			  SA.LeftReason,
			  SA.LCProgress,
			  SA.LCConduct,
			  SA.LCBook,
			  SA.LCNumber,
			  ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			  SA.LCRemark,
			  ISNULL(SA.LCCopy,0) AS LCCopy,
			  ISNULL(SA.LcId,0) AS LcId,
			  
			  ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			  ISNULL(SA.IsTransfer,0) AS IsTransfer,
			  ISNULL(SA.TransferFrom,'') AS TransferFrom,
			  ISNULL(SA.PassingYear,'') AS PassingYear,
			  ISNULL(SA.IsTFWS,0) AS IsTFWS,
			  ISNULL(SA.IsCertificateHolder,0) AS IsCertificateHolder,
			  ISNULL(SA.CertificateName,'') AS CertificateName,
			  ISNULL(SA.AdmissionQuotaId,0) AS AdmissionQuotaId,
			  ISNULL(SA.PreviousStandard,'') AS PreviousStandard,
			  ISNULL(SA.PreviousLCDate,'') AS PreviousLCDate,
			  ISNULL(SA.PreviousLCNumber,'') AS PreviousLCNumber,
			  ISNULL(SA.PreviousLCResult,'') AS PreviousLCResult,
			  ISNULL(SA.ProofOfDOB,'') AS ProofOfDOB,
			  ISNULL(SA.PreviousLeftDate,'') AS PreviousLeftDate			--add for 27789 mantis

  FROM 
         sStudent.tStudentAdmission SA
  WHERE 
		SA.StudentId = @rStudentId
END
GO
PRINT N'Altering Procedure [sAcademic].[pImportLessonPlan]...';


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

	DECLARE @lCount int,@intDoc INT,@lInterrorCode INT,@loXML XML,
			@lDivisionId int,
			@lTopicId int,
			@lNoOfPeriodRequired smallint,
			@lObjective nvarchar(1000),
			@lIndicativeHomework nvarchar(1000),
			@lSummary nvarchar(1000),
			@lStartDate date,
			@lEndDate date,
			@lIsCompleted bit,
			@lEmployeeId bigint,
			@lBatchId int,
			@lCreatedUserId bigint,
			@lCreatedDateTime datetime,
			@lUpdatedUserId bigint,
			@lUpdatedDateTime datetime,
			@lLearningExperience nvarchar(1000),
			@lToolsAndTechniques nvarchar(500),
			@lEssentialMaterial nvarchar(500),
			@lAssessmentQuestion nvarchar(1000),
			@lTeacherExample nvarchar(1000),
			@lGuidedPractice nvarchar(1000),
			@lIndependentPractice nvarchar(1000),
			@lSubTopic nvarchar(1000) ,
			@lSession nvarchar(100) ,
			@lTrainingMethod  nvarchar(100) ,
			@lPeriodCount int

	SET @loXML = CAST(@rXmldoc AS XML)
	
	
	CREATE TABLE #tTable1 (
	Id int IDENTITY,
	DivisionId int,
	TopicId int,
	NoOfPeriodRequired smallint,
	Objective nvarchar(1000),
	IndicativeHomework nvarchar(1000),
	Summary nvarchar(1000),
	StartDate date,
	EndDate date,
	IsCompleted bit,
	EmployeeId bigint,
	BatchId int,
	CreatedUserId bigint,
	CreatedDateTime datetime,
	UpdatedUserId bigint,
	UpdatedDateTime datetime,
	LearningExperience nvarchar(1000),
	ToolsAndTechniques nvarchar(500),
	EssentialMaterial nvarchar(500),
	AssessmentQuestion nvarchar(1000),
	TeacherExample nvarchar(1000),
	GuidedPractice nvarchar(1000),
	IndependentPractice nvarchar(1000),
	SubTopic nvarchar(1000),
	Session nvarchar(100) ,
	TrainingMethod  nvarchar(100) ,
	PeriodCount int)
	 
	INSERT INTO #tTable1(
			DivisionId
           ,TopicId
           ,NoOfPeriodRequired
           ,Objective
           ,IndicativeHomework
           ,Summary
           ,StartDate
           ,EndDate
           ,IsCompleted
           ,EmployeeId
		   ,BatchId
		   ,CreatedUserId
           ,LearningExperience
           ,ToolsAndTechniques
           ,EssentialMaterial
           ,AssessmentQuestion
           ,TeacherExample
           ,GuidedPractice
           ,IndependentPractice
           ,SubTopic
		   ,Session 
		   ,TrainingMethod
		   ,PeriodCount)
	SELECT
		 T.c.value('@DivisionId','int') AS DivisionId,
		 T.c.value('@TopicId','int') AS TopicId,
		 T.c.value('@PerioNo','smallint') AS NoOfPeriodRequired,
		 T.c.value('@Objective','nvarchar(1000)') AS Objective,
		 T.c.value('@IndicativeHomework','nvarchar(1000)') AS IndicativeHomework,
		 T.c.value('@Summary','nvarchar(1000)') AS Summary,
		 T.c.value('@StartDate','Date') AS StartDate,
		 T.c.value('@EndDate','Date') AS EndDate,
		 T.c.value('@Completed','bit') AS IsCompleted,
		 T.c.value('@EmployeeId','bigint') AS EmployeeId,
		 @rBatchId,
		 T.c.value('@CreatedUserId','bigint') AS CreatedUserId,
		 T.c.value('@LearningExperience','nvarchar(1000)') AS LearningExperience,
		 T.c.value('@ToolsAndTechniques','nvarchar(500)') AS ToolsAndTechniques,
		 T.c.value('@EssentialMaterial','nvarchar(500)') AS EssentialMaterial,
		 T.c.value('@AssessmentQuestion','nvarchar(1000)') AS AssessmentQuestion,
		 T.c.value('@TeacherExample','nvarchar(1000)') AS TeacherExample,
		 T.c.value('@GuidedPractice','nvarchar(1000)') AS GuidedPractice,
		 T.c.value('@IndependentPractice','nvarchar(1000)') AS IndependentPractice,
		 T.c.value('@SubTopic','nvarchar(1000)') AS SubTopic,
		 T.c.value('@Session','nvarchar(100)') AS Session ,
		 T.c.value('@TrainingMethod','nvarchar(100)') AS TrainingMethod,
		 T.c.value('@PeriodCount','int') AS PeriodCount

	FROM @loXML.nodes('/Table/ImportLessonPlan')T(c)
	
		SELECT @lCount =  COUNT(Id) FROM #tTable1
	
		-- Added for mantis: 0025563 By Foram
		DECLARE @lOrgGroupBatchId int=0, @lConfigValue nvarchar(50),@lIsLessonPlanOnSameDayAllow bit=0
		SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rBatchId
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 537 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)

		IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
		BEGIN 
			SET @lIsLessonPlanOnSameDayAllow = 0 
		END
		ELSE
		BEGIN
			SET @lIsLessonPlanOnSameDayAllow = 1
		END
		-- Added for mantis: 0025563 By Foram

		WHILE @lCount > 0 

		BEGIN				
	   
			SELECT	
				@lDivisionId = DivisionId,
				@lTopicId = TopicId,
				@lNoOfPeriodRequired = NoOfPeriodRequired,
				@lObjective = Objective,
				@lIndicativeHomework = IndicativeHomework,
				@lSummary = Summary,
				@lStartDate = StartDate,
				@lEndDate = EndDate,
				@lIsCompleted = IsCompleted,
				@lEmployeeId = EmployeeId,
				@lBatchId = BatchId,
				@lCreatedUserId = CreatedUserId,
				@lLearningExperience = LearningExperience,
				@lToolsAndTechniques = ToolsAndTechniques,
				@lEssentialMaterial = EssentialMaterial,
				@lAssessmentQuestion = AssessmentQuestion,
				@lTeacherExample = TeacherExample,
				@lGuidedPractice = GuidedPractice,
				@lIndependentPractice = IndependentPractice,
				@lSubTopic = SubTopic ,
				@lSession = Session ,
			    @lTrainingMethod  = TrainingMethod ,
			    @lPeriodCount = PeriodCount 
			FROM #tTable1 WHERE Id = @lCount 
			
			IF(@lIsLessonPlanOnSameDayAllow = 0)
			BEGIN
				IF EXISTS(SELECT Id FROM sAcademic.tLessonPlan WHERE DivisionId=@lDivisionId AND TopicId = @lTopicId AND StartDate = @lStartDate AND EndDate = @lEndDate)
				BEGIN
					Declare @lTopicName nvarchar(500), @lDivisionName nvarchar(100)
					SET  @lTopicName =(select Title from sAcademic.tTopicMaster where Id =@lTopicId)
					SET  @lDivisionName =(select Title from sSetup.tDivisionMaster Where Id =@lDivisionId)

					SELECT -101 AS Result, 'Lesson Plan Already Exists for for Division - '+@lDivisionName+', Topic - '+@lTopicName+', Start Date - '+Convert(nvarchar(10), @lStartDate, 103)+', End Date - '+Convert(nvarchar(10), @lEndDate, 103)+'' AS Message
					RETURN
				END 
			END
			DECLARE @lNextNumber BIGINT	
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output

			INSERT INTO sAcademic.tLessonPlan
				(
					Id,
					TopicId,
					DivisionId,
					NoOfPeriodRequired,
					Objective,
					IndicativeHomework,
					Summary,
					StartDate,
					EndDate,
					IsCompleted,
					EmployeeId,
					BatchId,
					CreatedUserId,
					CreatedDateTime,
					LearningExperience,
					ToolsAndTechniques,
					EssentialMaterial,
					AssessmentQuestion,
					TeacherExample,
					GuidedPractice,
					IndependentPractice,
					SubTopic ,
					Session ,
					TrainingMethod ,
					PeriodCount
				)
			VALUES
				(
					@lNextNumber,
					@lTopicId,
					@lDivisionId,
					ISNULL(@lNoOfPeriodRequired,0),
					ISNULL(@lObjective,''),
					ISNULL(@lIndicativeHomework,''),
					ISNULL(@lSummary,''),
					@lStartDate,
					@lEndDate,
					@lIsCompleted,
					@lEmployeeId,
					@lBatchId,
					@lCreatedUserId,
					sCommon.fGetDate(),
					ISNULL(@lLearningExperience,''),
					ISNULL(@lToolsAndTechniques,''),
					ISNULL(@lEssentialMaterial,''),
					ISNULL(@lAssessmentQuestion,''),
					ISNULL(@lTeacherExample,''),
					ISNULL(@lGuidedPractice,''),
					ISNULL(@lIndependentPractice,''),
					ISNULL(@lSubTopic,''),
					ISNULL(@lSession,''),
					ISNULL(@lTrainingMethod,''),
					ISNULL(@lPeriodCount,0)
				)
				
			SET @lCount = @lCount - 1
			SELECT 1 AS Result 		

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


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanAdd]
	 
        @rId bigint=0,
        @rTopicId int,
        @rDivisionId int, 
        @rNoOfPeriodRequired smallint,
        @rObjective nvarchar(1000),
        @rIndicativeHomework nvarchar(200),
        @rSummary nvarchar(200),
        @rStartDate date='',
        @rEndDate date='',
        @rIsCompleted bit=0,
        @rEmployeeId bigint,
        @rBatchId int,
        @rCreatedUserId bigint,
        @rOrgId smallint,
        @rLearningExperience nvarchar(1000)='',
        @rToolsAndTechniques nvarchar(500)='',
        @rEssentialMaterial nvarchar(500)='',
		@rAssessmentQuestion	nvarchar(1000)='',	
		@rTeacherExample	nvarchar(1000)='',
		@rGuidedPractice	nvarchar(1000)='',
		@rIndependentPractice	nvarchar(1000)	='',
		@rSubTopic nvarchar(1000)='' ,
	    @rSession nvarchar(100)='' ,
		@rTrainingMethod  nvarchar(100)='' ,
		@rPeriodCount int =0,
		@rRemark nvarchar(MAX) = ''
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	--IF(@rId = 0)	
	--BEGIN
	--	--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
	--	--	BEGIN
	--	--	select -102 as Result
	--	--	RETURN
	--	--END 
	
	--	If Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
	--END
	--ELSE
	--BEGIN
	--	--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
	--	--Begin
	--	--	select -102 as Result
	--	--	RETURN
	--	--End
	--	If  Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	-- Added for mantis: 0025563 By Foram
	DECLARE @lOrgGroupBatchId int=0, @lConfigValue nvarchar(50),@lIsLessonPlanOnSameDayAllow bit=0
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rBatchId
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 537 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	BEGIN 
		SET @lIsLessonPlanOnSameDayAllow = 0 
	END
	ELSE
	BEGIN
		SET @lIsLessonPlanOnSameDayAllow = 1
	END
	-- Added for mantis: 0025563 By Foram

	IF(@lIsLessonPlanOnSameDayAllow = 0)
	BEGIN
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT Id FROM sAcademic.tLessonPlan WHERE DivisionId=@rDivisionId AND TopicId = @rTopicId AND StartDate = @rStartDate AND EndDate = @rEndDate)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END 
		END
		ELSE
		BEGIN
			IF  EXISTS(SELECT Id FROM sAcademic.tLessonPlan WHERE DivisionId=@rDivisionId AND TopicId = @rTopicId AND StartDate = @rStartDate AND EndDate = @rEndDate AND Id <> @rId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
		END
	END

	DECLARE @lNextNumber BIGINT 

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

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tLessonPlan
	    SET
			TopicId=@rTopicId,
			DivisionId=@rDivisionId,
			NoOfPeriodRequired=@rNoOfPeriodRequired,
			Objective=@rObjective,
			IndicativeHomework=@rIndicativeHomework,
			Summary=@rSummary,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			IsCompleted=@rIsCompleted,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			LearningExperience = @rLearningExperience,
			ToolsAndTechniques = @rToolsAndTechniques,
			EssentialMaterial =@rEssentialMaterial,
			EmployeeId = @rEmployeeId,
			AssessmentQuestion=@rAssessmentQuestion,
			TeacherExample=@rTeacherExample,
			GuidedPractice=@rGuidedPractice,
			IndependentPractice=@rIndependentPractice,
			SubTopic= CASE WHEN @rSubTopic = '-1' Then '' ELSE @rSubTopic END ,
			[Session] = @rSession ,
			TrainingMethod =@rTrainingMethod ,
			PeriodCount =@rPeriodCount,
			Remark=@rRemark
	      WHERE Id = @rId
	      SELECT 11 AS Result, @lNextNumber As Id
	 END  	

END
GO
PRINT N'Altering Procedure [sActivity].[pEmployeeHealthCheckupEntryGet]...';


GO
ALTER PROCEDURE [sActivity].[pEmployeeHealthCheckupEntryGet]
	            
           @rHealthCheckupId int,
           @rStatusId int=0,
           @rBatchId int,
           @rDepartmentId int          
	
WITH EXECUTE AS CALLER	
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
	SELECT      
		ISNULL([HealthCheckupId],0) AS HealthCheckupId
		,ISNULL([HeightInCm],0) AS HeightInCm 
		,ISNULL([WeightInKg],0) AS WeightInKg
		,ISNULL([Dental],'') AS Dental
		,ISNULL([Nails],'') AS Nails
		,ISNULL([Hair],'') AS Hair
		,ISNULL([Skin],'') AS Skin
		,ISNULL([Ear],'') AS Ear
		,ISNULL([Nose],'') AS Nose
		,ISNULL([Throat],'') AS Throat
		,ISNULL([Respiratory],'') AS Respiratory
		,ISNULL([Cardiovascular],'') AS Cardiovascular
		,ISNULL([Nervous],'') AS Nervous
		,ISNULL([Eye],'') AS Eye
		,ISNULL([Other],'') AS Other
		,ISNULL([ImportantFinding],'') AS ImportantFinding
		,ISNULL([Remarks],'') AS Remarks
		,ISNULL([FollowupDetail],'') AS FollowupDetail
		,ISNULL(HT.[StatusId],0) AS StatusId
		,EC.EmployeeId AS EmployeeId
		,EC.EmployeeName AS EmployeeName
		,EC.Code AS EmployeeCode
		,EC.DepartmentId
		,EC.DepartmentName AS DepartmentName
		,EC.MobileNumber As MobileNumber
		,ISNULL(HT.BloodGroupId,0)AS BloodGroupId
			  
	FROM	sHrm.vEmployeeCommunication EC
		LEFT JOIN [sActivity].[tHealthCheckupEmployee] HT ON EC.EmployeeId = HT.EmployeeId	AND (HT.HealthCheckupId = @rHealthCheckupId  )
    	--INNER JOIN sCommon.tStatusMaster SMM ON SMM.Id = HT.StatusId	    		
  
	WHERE  (EC.StatusId = @rStatusId OR @rStatusId = 0)
		-- AND (HC.BatchId = @rBatchId OR @rBatchId = 0)
		 ANd (EC.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			
	ORDER BY EC.Code ASC
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sActivity].[pHealthCheckupEmployeeGet]...';


GO
ALTER PROCEDURE [sActivity].[pHealthCheckupEmployeeGet]
	        
	       @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='',     
           @rEmployeeId bigint,
           @rHealthCheckupId int,
           @rStatusId int,
           @rBatchId int,
           @rFromDate date = null,
           @rToDate date = null,
           @rDepartmentId int,
		   @rOrgId int  = 0         
	
WITH EXECUTE AS CALLER	
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
  SELECT      
			  @rBuilder1 AS Builder1
			  ,@rBuilder2 AS Builder2
			  ,[HealthCheckupId]     
	          ,HT.EmployeeId 
			  ,ISNULL([HeightInCm],0) AS HeightInCm 
			  ,ISNULL([WeightInKg],0) AS WeightInKg
			  ,[Dental]
			  ,[Nails]
			  ,[Hair]
			  ,[Skin]
			  ,[Ear]
			  ,[Nose]
			  ,[Throat]
			  ,[Respiratory]
			  ,[Cardiovascular]
			  ,[Nervous]
			  ,[Eye]
			  ,[Other]
			  ,[ImportantFinding]
			  ,[Remarks]
			  ,[FollowupDetail]
			  ,HT.[StatusId]	
			  ,EC.EmployeeId AS EmployeeId
			  ,EC.EmployeeName AS EmployeeName
			  ,EC.Code AS EmployeeCode
			  ,EC.DepartmentId
			  ,EC.DepartmentName AS DepartmentName
			  ,ISNULL(EPD.GenderId,0) AS GenderId
			  ,EC.MobileNumber As MobileNumber
			  ,BGM.Title AS BloodGroup
			  ,SMM.Title AS Status
			  ,HC.Title AS HealthCheckup
			  ,HC.DoctorName
			  ,HC.CheckupDate
			  ,ISNULL(HT.BloodGroupId,0)AS BloodGroupId
			  ,ISNULL(BGM.Title,'') AS BloodGroup
			  
  FROM		[sActivity].[tHealthCheckupEmployee] HT 
			INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId = HT.EmployeeId	
    		INNER JOIN sCommon.tStatusMaster SMM ON SMM.Id = HT.StatusId	
    		INNER JOIN sActivity.tHealthCheckup HC ON HC.Id = HT.HealthCheckupId  
    		LEFT JOIN [sHrm].[tEmployeePersonalDetail] EPD ON EPD.EmployeeId = EC.EmployeeId
    		LEFT JOIN sCommon.tBloodGroupMaster BGM ON EPD.BloodGroupId=BGM.Id
    		    		
  
  WHERE  (HT.HealthCheckupId = @rHealthCheckupId OR @rHealthCheckupId = 0)	
	     AND (HT.EmployeeId = @rEmployeeId OR @rEmployeeId =  0)
	     AND (HT.StatusId = @rStatusId OR @rStatusId = 0)
         AND (HC.CheckupDate >= @rFromDate OR ISNULL(@rFromDate,'') = '')
		 AND (HC.CheckupDate <= @rToDate OR ISNULL(@rToDate,'') = '')
		 AND (HC.BatchId = @rBatchId OR @rBatchId = 0)
		 AND (EC.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		 AND (EC.OrgId = @rOrgId OR @rOrgId = 0)
			
		ORDER BY CheckupDate ASC
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sActivity].[pMyEventGet]...';


GO
ALTER PROCEDURE [sActivity].[pMyEventGet]
	 
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rFromDate date='',
	 @rTodate date='',
	 @rEventTypeId int = 0
	 --@rSyncedEventScheduleId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	IF(@rSourceTypeId=2003)
	BEGIN
	
	DECLARE @DivisionId int
	
	SELECT @DivisionId = DivisionId  FROM sStudent.tAcademic WHERE StudentId=@rSourceId 
					AND OrgId=@rOrgId AND BatchId=@rBatchId 
	
		SELECT
				ISNULL(EE.Id,0) AS Id,
				ES.Id AS EventScheduleId,
				ES.Title,
				ES.FromDate,
				ES.ToDate,
				ES.IsCommonForAll,
				ES.IsHoliday,
				ES.IsEnrollment,
				ES.CreatedDateTime,
				ES.Remark AS Remark,
				EE.Remark AS EventEnrollmentRemark
		FROM 
			sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventEnrollment EE ON EE.EventScheduleId=ES.Id AND EE.SourceId=@rSourceId AND EE.SourceTypeId=2003
		WHERE 
	        
			 ((ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2005 AND 
				SourceId= @DivisionId )) OR ES.ISCommonForAll = 1)
					
		AND (ES.BatchId=@rBatchId) 
		AND ((Convert(date,ES.FromDate)<=@rFromDate) OR ISNULL(@rFromDate,'')='')
		AND ((Convert(date,ES.Todate)>=@rTodate) OR ISNULL(@rTodate,'')='')
		AND (ES.EventTypeId = @rEventTypeId OR @rEventTypeId = 0)
		--AND (ES.Id > @rSyncedEventScheduleId OR @rSyncedEventScheduleId = 0)
		ORDER BY ES.FromDate DESC
		
		
		
	END
	ELSE
	BEGIN
		SELECT
				ISNULL(EE.Id,0) AS Id,
				ES.Id AS EventScheduleId,
				ES.Title,
				ES.FromDate,
				ES.ToDate,
				ES.IsCommonForAll,
				ES.IsHoliday,
				ES.IsEnrollment,
				ES.CreatedDateTime,
				ES.Remark AS Remark,
				EE.Remark AS EventEnrollmentRemark
		FROM 
				sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventEnrollment EE ON EE.EventScheduleId=ES.Id AND EE.SourceId=@rSourceId AND EE.SourceTypeId=95
		WHERE 
	  
			 --(ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2004 AND 
				--SourceId=(SELECT OrganizationDepartmentId FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId))) 

				 (ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId in(2004,95) AND 
				((SourceId=(SELECT OrganizationDepartmentId FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId)) or
				(SourceId=@rSourceId)))) 

		AND (ES.BatchId=@rBatchId)
	   AND ((Convert(date,ES.FromDate)<=@rFromDate) OR ISNULL(@rFromDate,'')='')
		AND ((Convert(date,ES.Todate)>=@rTodate) OR ISNULL(@rTodate,'')='')
		AND (ES.EventTypeId = @rEventTypeId OR @rEventTypeId = 0)
		--AND (ES.Id > @rSyncedEventScheduleId OR @rSyncedEventScheduleId = 0)
		ORDER BY ES.FromDate DESC
	END
END
GO
PRINT N'Altering Procedure [sAdmission].[pRptAdmissionListUserWiseGet]...';


GO
ALTER PROCEDURE [sAdmission].[pRptAdmissionListUserWiseGet]
	
	
	 @rBatchId int,
	 @rClassId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate date,
	 @rToDate date,
	 @rIsDetail bit =0,
	 @rCreatedUserName nvarchar(100)=''
AS
 SET NOCOUNT ON
			 

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

	SELECT 
		 AF.FormNo,
		 AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
		 AF.ForClassId,
		 AF.BatchId,
		 AF.OrgId,
		 AF.City,
		 AF.FamilyCast,
		 CM.Title AS Class,
		 AF.FamilySubCast,
		 AF.CastCategoryId,
		 --for online and offline display same feename
		 AC.FormFeeName AS FeeName,
		 --in online entry display amount from pt  and in offline entry amount display from aff
		 CASE WHEN AF.DataEntryModeId = 561 THEN PT.PayAmount ELSE AFF.FeeAmount END  AS FeeAmount,
		 @rIsDetail AS IsDetail,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 ISNULL(AF.CreatedDateTime,'') AS CreatedDateTime,
		 ISNULL(U.DisplayTitle,'') AS UserName
	 
	 FROM 
		sAdmission.tAdmissionForm AF	
		INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId=CM.Id
		LEFT JOIN sAdmission.tAdmissionFormFee AFF ON AFF.AdmissionFormId = AF.Id
		LEFT JOIN sAdmission.tAdmissionCriteriaFee ACF ON ACF.Id = AFF.AdmissionCriteriaFeeId
		INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id AND AC.BatchId = @rBatchId
		LEFT JOIN sOp.tPaymentTransaction PT ON AF.Id = PT.PayerSourceId AND PT.TransactionSourceTypeId = 2027 AND PT.TransactionStatusId IN (2,4)
		INNER JOIN sSecurity.tUser U ON U.Id=AF.CreatedUserId
	WHERE 	
		AF.BatchId=@rBatchId
		--AND AF.OrgId=@rOrgId
		AND ((AF.ForClassId=@rClassId) OR (@rClassId=0))	
		AND ((CONVERT(DATE,AF.CreatedDateTime) >= @rFromDate) OR (isnull(@rFromDate,'')=''))
	    AND ((CONVERT(DATE,AF.CreatedDateTime) <= @rToDate) OR (isnull(@rToDate,'')=''))
		AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	    ORDER BY AF.FormNo
END
GO
PRINT N'Altering Procedure [sAlert].[pClassworkStudentListGet]...';


GO
ALTER PROCEDURE [sAlert].[pClassworkStudentListGet]
	 
		 @rDivisionId bigint,
		 @rOrgId int,
	 	 @rBatchId int,	 	 	 	
	 	 @rTemplate nvarchar(max) 	,
		 @rMailSubject nvarchar(500)='',
		 @rSubjectId bigint,
		 @rClassworkId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
		SC.OrgGroupId,
		SC.OrgId,
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		--@rTemplate AS MsgText,
		(replace
			(replace
				(replace
					(replace
						(replace(@rTemplate,'[TeacherName]',EM.FirstName +''+EM.MiddleName+''+EM.LastName), 
					'[SubjectName]',SM.Title),
				'[ClassWork]',AC.Classwork), 
			'[HomeWork]',AC.Homework), 
		'[HomeworkEndDate]',AC.HomeWorkEndDate)) AS MsgText,
		'2003' AS SourceTypeId,
		SC.StudentId AS SourceId,
		2003 AS ReceiverSourceTypeId,
		SC.StudentId AS ReceiverSourceId,
		@rMailSubject AS Subject,
		AC.ClassId,
		AC.DivisionId,
		AC.SubjectId,
		EM.FirstName +''+EM.MiddleName+''+EM.LastName AS TeacherName,
		SM.Title AS SubjectName,
		AC.Classwork,
		AC.Homework,
		AC.HomeWorkEndDate,
		SC.WhatsAppContactNo,
		AC.Id AS DocumentId
				
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sAcademic.tClasswork AC ON AC.ClassId = SC.ClassId AND AC.DivisionId=SC.DivisionId AND AC.BatchId =SC.BatchId
		INNER JOIN sStudent.vStudentAcademic SA  ON SC.AcademicId=SA.AcademicId AND SC.ClassId=SA.ClassId AND SC.DivisionId=SA.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId AND OM.Id=SC.OrgId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = AC.SubjectId
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=AC.EmployeeId
	WHERE (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
		AND (SC.DivisionId = @rDivisionId)
		AND (AC.SubjectId=@rSubjectId)
		AND AC.Id = @rClassworkId
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricAbsentTimeGet]...';


GO

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

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare  @lBatchID INT
			SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1

			--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),'')
			--For Optimization

			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL
				)

			insert #tShift
			Select 
				ShiftCode
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			--AND IsOutTimeAlertTime=1
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<=cast([sCommon].[fGetDate]() as Time)
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(DATEADD(MINUTE,-@rIntervalTime,[sCommon].[fGetDate]()) as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<=cast(@rToDateTime as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(@rFromDateTime as Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) 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,
						CreatedDateTime [datetime] NOT NULL,--For Optimization
						AutoId bigint not null--For Optimization
					)

			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MIN(In_Out_Time),SourceTypeId
				,min(CDT.CreatedDateTime),min(CDT.Autoid) --For Optimization
				from [sBiometric].[tCloudTransactionData] CDT
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode 
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 
				--For Optimization
				AND CDT.Autoid>@lCloudTransactionDataId
				AND CDT.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
			END
			
			--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 
				sHrm.vEmployeeCommonDetail EM 
				Inner Join  [sHrm].[tEmployeeMaster] E on EM.EmployeeId=E.Id
				INNER JOIN #tShift tempshift ON tempshift.ShiftCode=E.ShiftId
				LEFT JOIN #tTable temp ON  temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				LEFT JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				EM.OrgID =@rOrgId
				AND temp.In_Out_Time is null
				AND E.StatusId = 7  -- Added
				AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),@lBatchID ,OrganizationDepartmentId ,@rOrgId )<>'W')
				AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),@lBatchID ,OrganizationDepartmentId ,@rOrgId )<> 'H')

			
			--select * from #tTable
				select 
					MobileNo,	
					EmailId,
					replace (
					replace(@lSMSTemplete,'[EmployeeName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS SMSText,
					replace (
					replace(@lMailTemplete,'[EmployeeName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS MailText,
					replace (
					replace(@lNotificationTemplete,'[EmployeeName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS NotificationText,
					replace (
					replace(@lWhatsappTemplete,'[EmployeeName]',StudentName),					
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS WhatsappText,
					Subject,
					ReceiverSourceTypeId,
					ReceiverSourceId,
					StudentName AS EmployeeName,
					Code,
					WhatsAppContactNo,
					SourceTypeId,
					SourceId,
					OrgId,
					OrganizationTitle
				FROM  
					sBiometric.tTempBiometricAlertData
				where 
					AlertUniqueId=@AlertUniqueId
			--For Optimization

			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].[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),'')
			--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
					)
			--if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,cast(SMC.OutTimeAlertTime as time),Max(CreatedDateTime) 
				from [sBiometric].[tCloudTransactionData] CDT 
				INNER JOIN sBiometric.tShiftMasterCloud SMC on SMC.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 
				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,[sCommon].[fGetDate](),108),''))
					 AS SMSText,
					replace (
					replace(@lMailTemplete,'[EmployeeName]',StudentName),
					'[TimeStamp]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),108),''))
					 AS MailText,
					replace (
					replace(@lNotificationTemplete,'[EmployeeName]',StudentName),
					'[TimeStamp]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),108),''))
					 AS NotificationText,
					replace (
					replace(@lWhatsappTemplete,'[EmployeeName]',StudentName),					
					'[TimeStamp]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),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)=''
	 	 
	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=137 AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=137 AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=137 AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=137 AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')

	IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime) > 0)
	BEGIN
	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),
					''[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='+@lShiftColumntName+'
		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].[pNewQueryDetailsGet]...';


GO
ALTER PROCEDURE [sAlert].[pNewQueryDetailsGet]
	 	 
	 	 @rQueryId bigint,	 	 
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rFromSourceTypeId smallint,
		 @rOrgId int,
		 @rQueryFrom nvarchar(200)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @AssignedTo bigint;
	DECLARE @AssignedToEmailId varchar(100);
	
	IF(@rQueryFrom = 'Query')
	BEGIN
	IF(@rFromSourceTypeId=2003)
	BEGIN
		   SELECT 
			 QM.Id AS QueryId,
		     (ISNULL(SC.ParentEmail,'')) AS EmailId,
		    -- 'mohit.patel@vidyalayaschoolsoftware.com' AS EmailId,
		     ISNULL(SC.ParentContactNo,'') AS MobileNo,
		     replace(replace(@rTemplate,'[Name]',SC.Name),'[QueryNo]',QM.number) AS MsgText,
		     @rSubject AS Subject,
			 2003 AS ReceiverSourceTypeId,
			 SC.StudentId AS ReceiverSourceId,
			 OM.Id AS OrgId,
			 OM.OrgGroupId,
			 2003 AS SourceTypeId,
			 SC.StudentId AS SourceId  ,
			 SC.Name AS Name,
			 QM.number AS QueryNo,
			 SC.WhatsAppContactNo,
			 QM.Id AS DocumentId
			
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN [sStudent].[vStudentCommunication] SC ON QM.FromSourceId=SC.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SC.OrgId
			
		
	      WHERE
		    QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId AND BM.IsActive=1 AND SC.IsBlockAllAlert=0
	END
   
    IF(@rFromSourceTypeId=95)
	BEGIN
		
		   SELECT 
		     QM.Id AS QueryId,
		     (ISNULL(EM.CompanyEmail,'')) AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		     replace(replace(@rTemplate,'[Name]',EM.EmployeeName),'[QueryNo]',QM.number) AS MsgText,
		     @rSubject AS Subject,
		     95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 OM.Id AS OrgId,
			 OM.OrgGroupId,
			 95 AS SourceTypeId,
			 EM.EmployeeId AS SourceId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			 QM.Id AS DocumentId
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		
	      WHERE
		    QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId
		
	END
		
	IF(@rFromSourceTypeId=96)
	BEGIN
		
		   SELECT 
		     QM.Id AS QueryId,
		     (ISNULL(EM.CompanyEmail,'')) AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		     replace(replace(@rTemplate,'[Name]',EM.EmployeeName),'[QueryNo]',QM.number) AS MsgText,
		     @rSubject AS Subject,
		     96 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 OM.Id AS OrgId,
			 OM.OrgGroupId,
			 96 AS SourceTypeId,
			 EM.EmployeeId AS SourceId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			 QM.Id AS DocumentId
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.AssignedToEmployeeId=EM.EmployeeId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		
	      WHERE
		    QM.Id = @rQueryId 
		
		END
	END
	--Alert from My Query
	ELSE
	BEGIN
		SELECT 
		     QM.Id AS QueryId,
		     ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
			 replace(replace(@rTemplate,'[Name]',EM.EmployeeName),'[QueryNo]',QM.number) AS MsgText,
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 QM.OrgGroupId,
			 @rOrgId AS OrgId,
			 EM.EmployeeId AS SourceId,
			 95 AS SourceTypeId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			 QM.Id AS DocumentId
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id = QM.QueryCategoryId
			INNER JOIN sCommunication.tQueryCategoryAssignedTo QCA ON QCA.QueryCategoryId = QCM.Id
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = QCA.SourceId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		
	      WHERE
		    QM.Id = @rQueryId 
	END
		
END
GO
PRINT N'Altering Procedure [sAlert].[pQueryCommentGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pQueryCommentGet]
	 	 
		 @rOrgId int,
	 	 @rQueryId bigint,	 	 
	 	 @rSubject nvarchar(100),
		 @rRemark nvarchar(1000),
	 	 @rTemplate nvarchar(max),
	 	 @rFromSourceTypeId smallint,
		 @rQueryFrom varchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rQueryFrom = 'QueryList')
	BEGIN
	   SELECT 
			 QM.Id AS QueryId,
		     ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		    replace (	
		      replace (	
				 replace (
				         replace(
				                  --@rTemplate,'[User]',EM.EmployeeName),
								   @rTemplate,'[User]',
								   CASE WHEN @rFromSourceTypeId = 2003 THEN 'Student' 
								   WHEN @rFromSourceTypeId = 95 THEN 'Employee' 
								   ELSE 'Admin' END),
								  '[Comment]',@rRemark),
								  --'[Time]',QM.CreatedDateTime),
								  '[Time]',GetDate()),
								  '[Query]',QM.Title) 
				            AS MsgText,
		     
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 QM.OrgGroupId,
			 @rOrgId AS OrgId,
			 EM.EmployeeId AS SourceId,
			 95 AS SourceTypeId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id = QM.QueryCategoryId
			INNER JOIN sCommunication.tQueryCategoryAssignedTo QCA ON QCA.QueryCategoryId = QCM.Id
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = QCA.SourceId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
	      WHERE
		    QM.Id = @rQueryId 
	END
	ELSE
	BEGIN
	IF(@rFromSourceTypeId=2003)
		BEGIN
	
		 SELECT 
			QM.Id AS QueryId,
		    ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			replace (	
				replace (
				    replace (
				         replace(
				                  --@rTemplate,'[User]',SC.Name),
								  @rTemplate,'[User]','Student'),
								   '[Comment]',@rRemark),
								   --'[Time]',QM.CreatedDateTime),
								   '[Time]',GetDate()),
								 '[Query]',QM.Title) 
				            AS MsgText,
		     
		       @rSubject AS Subject,
			   2003 AS ReceiverSourceTypeId,
			   SC.StudentId AS ReceiverSourceId  ,
			   SC.Name AS Name,
			   (CASE WHEN QM.StatusId = 209 THEN 'Open' WHEN QM.StatusId = 210 THEN 'Closed' WHEN QM.StatusId = 709 THEN 'Hold' ELSE '' END) [Status],
				QM.number AS QueryNo,
				SC.WhatsAppContactNo,
				QM.OrgGroupId,
				@rOrgId AS OrgId,
				SC.StudentId AS SourceId,
				2003 AS SourceTypeId
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN [sStudent].[vStudentCommunication] SC ON QM.FromSourceId=SC.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId

	      WHERE
		    QM.Id = @rQueryId AND BM.IsActive=1 
		
		END
   
   IF(@rFromSourceTypeId=95)
		BEGIN
			SELECT 
			QM.Id AS QueryId,
		    ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		    ISNULL(EM.MobileNumber,'') AS MobileNo,
		    replace (	
		      replace (	
				 replace (
				         replace(
				                  --@rTemplate,'[User]',EM.EmployeeName),
								   @rTemplate,'[User]','Employee'),
								  '[Comment]',@rRemark),
								  --'[Time]',QM.CreatedDateTime),
								  '[Time]',GetDate()),
								  '[Query]',QM.Title) 
				            AS MsgText,
		     
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 QM.OrgGroupId ,
			 @rOrgId AS OrgId ,
			 EM.EmployeeId AS SourceId,
			 95 AS SourceTypeId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		
	      WHERE
		    QM.Id = @rQueryId 

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


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricAbsentTimeGet]
	@rOrgId int,
	@rOrgGroupId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)='',
	@rIntervalTime int=0,
	@rToDateTime dateTime=null,
	@rFromDateTime DateTime=null,
	@rEventId int=136

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare  @lBatchID INT
			SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1
			
			--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=2003),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),'')
			--For Optimization

			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL
				)

			insert #tShift
			Select 
				ShiftCode
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			--AND IsOutTimeAlertTime=1
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<cast([sCommon].[fGetDate]() as Time)
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(DATEADD(MINUTE,-@rIntervalTime,[sCommon].[fGetDate]()) as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<cast(@rToDateTime as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(@rFromDateTime as Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) 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,
						CreatedDateTime [datetime] NOT NULL,--For Optimization
						AutoId bigint not null--For Optimization
					)

			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MIN(In_Out_Time),SourceTypeId,
				min(CDT.CreatedDateTime),min(CDT.Autoid) --For Optimization
				from [sBiometric].[tCloudTransactionData] CDT with (nolock) 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode 
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 
				-- For Optimization
				AND CDT.Autoid>@lCloudTransactionDataId
				AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=136 and SourceTypeId=2003 and cast(CreatedDateTime as date)=CONVERT(date,[sCommon].[fGetDate]()))
				-- For Optimization
				Group by SourceId,SourceTypeId
			END

			-- For Optimization
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				'' as MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.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 
				sStudent.vStudentCommunication SC 
				Inner Join  [sStudent].[tStudentMaster] SM on SM.Id=SC.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
				INNER JOIN #tShift tempshift ON tempshift.ShiftCode=SM.ShiftId
				LEFT JOIN #tTable temp ON  temp.SourceId=SC.StudentId 
				where 
					SC.OrgID =@rOrgId
					AND SC.IsActiveBatch=1
					AND SC.StatusId = 1
					AND temp.In_Out_Time is null
					AND ([sAttendance].[fWeekHOffGet](YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),SC.BatchId,SC.ClassId,SC.DivisionId, '',@rOrgId)<>'W')
					AND ([sAttendance].[fWeekHOffGet](YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),SC.BatchId,SC.ClassId,SC.DivisionId, '',@rOrgId)<>'H')
		
				select 
					MobileNo,	
					EmailId,
					replace (
					replace(@lSMSTemplete,'[StudentName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS SMSText,
					replace (
					replace(@lMailTemplete,'[StudentName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS MailText,
					replace (
					replace(@lNotificationTemplete,'[StudentName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS NotificationText,
					replace (
					replace(@lWhatsappTemplete,'[StudentName]',StudentName),					
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS WhatsappText,
					Subject,
					ReceiverSourceTypeId,
					ReceiverSourceId,
					StudentName,
					Code,
					WhatsAppContactNo,
					SourceTypeId,
					SourceId,
					OrgId,
					OrgGroupId,
					OrganizationTitle
				FROM  
					sBiometric.tTempBiometricAlertData
				where 
					AlertUniqueId=@AlertUniqueId
			--For Optimization

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


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricFirstInTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime,
	@rEventId int=129

	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare @lDateTimeNow datetime=[sCommon].[fGetDate]()
			declare @lLastStudentFirstInAlertSendTime datetime

			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=2003),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 ),'')
		
			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,

			)
			insert into #tTable
			select CDT.SourceId,min(CDT.In_Out_Time),CDT.SourceTypeId,min(CDT.CreatedDateTime),min(CDT.Autoid)
			from [sBiometric].[tCloudTransactionData] CDT with (nolock) 
			inner join sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode=CDT.ShiftCode
			WHERE CDT.Attn_Dt=CONVERT(date,@lDateTimeNow)  AND CDT.SourceTypeId=2003
				AND (isnull(SMC.IsStopInTimeAlertTime,0)=0 OR (SMC.IsStopInTimeAlertTime=1 
				--AND CAST(SMC.StopInTimeAlertTime as Time)>=CAST(@rFromDateTime AS Time)
				AND  CAST(SMC.StopInTimeAlertTime as Time)>=CAST(CDT.In_Out_Time AS Time))
				
				)
				AND CDT.Autoid>@lCloudTransactionDataId
				AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=2003 AND cast(CreatedDateTime as date)=CONVERT(date,@lDateTimeNow))
			 Group by CDT.SourceId,CDT.SourceTypeId
	
			--select * from #tTable 
			print @lCloudTransactionDataId
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				'' as MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.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 sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				--temp.CreatedDateTime < @rToDateTime
				--AND temp.CreatedDateTime >= @rFromDateTime
				--AND 
				SC.OrgID =@rOrgId
				AND SC.StatusId = 1

			SELECT 
				MobileNo AS MobileNo,	
				EmailId AS EmailId,
				replace (
				replace (
				replace (
				replace(@lSMSTemplete,'[StudentName]',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,'[StudentName]',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,'[StudentName]',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,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS WhatsappText,
				Subject AS Subject,
				2003 AS ReceiverSourceTypeId,
				ReceiverSourceId AS ReceiverSourceId,
				StudentName AS StudentName,
				Code AS Code,
				WhatsAppContactNo AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SourceId AS 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].[pStudentBiometricLastOutTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime
	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=130 and SourceTypeId=2003),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=130 AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 1),'')
			

			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,
				LastOutAlertBasedOnId int NOT NULL,
				ShiftCode int NOT NULL,
				AutoId bigint not null,
			)
			
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,SMC.OutTimeAlertTime,Max(CreatedDateTime),SMC.LastOutAlertBasedOnId,CDT.ShiftCode,max(CDT.Autoid)
				from [sBiometric].[tCloudTransactionData] CDT with (nolock)  
				--inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				 INNER JOIN sBiometric.tShiftMasterCloud SMC on SMC.ShiftCode=CDT.ShiftCode
				where  Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())
					AND	((SMC.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
					AND SMC.IsOutTimeAlertTime=1
					AND CDT.SourceTypeId=2003 
					AND (
							(
								(LastOutAlertBasedOnId=1 OR (LastOutAlertBasedOnId=2  and CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time)<=cast(CDT.In_Out_Time as Time)
								AND CAST(OutTimeAlertTime AS Time) > CAST(CDT.In_Out_Time AS Time)))
								 AND CAST(OutTimeAlertTime AS Time)<cast(@rToDateTime as Time) 
								AND CAST(OutTimeAlertTime AS Time) > CAST(@rFromDateTime AS Time) 
							)
							OR
							(
							LastOutAlertBasedOnId=3 AND CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time)<=cast(CDT.In_Out_Time as Time)
							AND CAST(OutTimeAlertTime AS Time) > CAST(CDT.In_Out_Time AS Time)
							--AND CDT.Autoid>@lCloudTransactionDataId 
							AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=130 and SourceTypeId=2003 and cast(CreatedDateTime as date)=CONVERT(date,[sCommon].[fGetDate]()))
							)
						)
				Group by SourceId,SourceTypeId,SMC.OutTimeAlertTime,SMC.LastOutAlertBasedOnId,CDT.ShiftCode
				--select * from #tTable

			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				'' as MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				130,
				@AlertUniqueId
			FROM 
				#tTable temp
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				 
				SC.OrgID =@rOrgId
				AND SC.StatusId = 1



			SELECT 
				MobileNo AS MobileNo,	
				EmailId AS EmailId,
				replace (
				replace (
				replace (
				replace(@lSMSTemplete,'[StudentName]',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,'[StudentName]',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,'[StudentName]',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,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS WhatsappText,
				Subject AS Subject,
				2003 AS ReceiverSourceTypeId,
				ReceiverSourceId AS ReceiverSourceId,
				StudentName AS StudentName,
				Code AS Code,
				WhatsAppContactNo AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SourceId AS 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].[pStudentBiometricLateTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricLateTimeGet]
	 	 
	 	 @rOrgId int,
		@rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)=''
	 	 
	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=137 AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
	set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=137 AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
	set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=137 AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
	set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=137 AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=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+'
		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].[pRptCSExamMarkEntryGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptCSExamMarkEntryGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rBatchId int,
	  --@rCCECSId int,
	  @rFilter int,
	  @rBuilder nvarchar(max)='',
	  @rCCECAGroupId int=0,
	  @rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
SELECT
    @rBuilder AS Builder,
    SA.AcademicId,
    SA.Code,
    SA.Name,
    AM.Title,
    SA.RollNo AS RollNo ,
    CASE WHEN @rFilter=1 THEN ISNULL(AIS.ObtianMark,0) 
    ELSE  ISNULL(AIS.ConvertedMark,0) END AS TotalMark,
	(CASE EM.IsDisplayPhoto WHEN 1 THEN
	SI.StudentPhoto
	ELSE NULL END)AS StudentPhoto,
	EM.IsDisplayPhoto,
	EM.IsOnPrePrinted,
	ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
	(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
	OI.MarksheetHeaderA4 
	ELSE 
	NULL END) AS MarksheetHeaderA4,
	CCGM.Id AS CCECSGroupId,
	CCGM.Title AS CCECSGroupTitle,
    CA.OrderIndex AS CCECSGroupOrderIndex
    
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	 INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id 
	 AND CL.ClassID=@rClassId
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id 
	AND AIS.ExamId= @rExamId 
	AND (AIS.CCECSId =@rCCECSId OR @rCCECSId = 0) 
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = AIS.ExamId
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sAssessment.tCCECSGroupMaster CCGM ON CCGM.Id = AM.CCECAGroupId AND CCGM.OrgId = SA.OrgId --New Join Mantis : 0027514	
	WHERE 
	SA.ClassId=@rClassId
	And SA.DivisionId = @rDivisionID	
	And SA.BatchId = @rBatchId
	And (AM.CCECAGroupId= @rCCECAGroupId  OR @rCCECAGroupId  = 0 )
	Order by AM.OrderIndex
	END
GO
PRINT N'Altering Procedure [sAssessment].[pRptCSExamScoreGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptCSExamScoreGet]
	  
	   @rOrgId int
	  ,@rExamId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rBatchId int,
	  @rCCECAGroupId int=0,
	  @rCCEMasterId int=0,
	  @rAcademicId bigint=0,
	  @rBuilder1 nvarchar(max)=''
	  
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
			SELECT 		
				--ISNULL(CGM.Title,'') AS CSGroup,
				--ISNULL(CM.Title,'') AS CS,				
				--ISNULL(CC.Grade,'')  AS Grade,
				--ISNULL(CC.GradeIndicator,'') AS Indicator,
				--ISNULL(CC.DescriptiveIndicator,'')  AS DescriptiveIndicator,			
				--ISNULL(SA.AcademicId,0) AS AcademicId,
				--ISNULL(CC.IndicatorIds,'') AS IndicatorIds,
				--CGM.GradeSetId,
				--CM.Id as CMID
				
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.Grade,'') AS Term1Indicator,
				 CCEM.Title AS GroupTitle,
				 AM.Title AS MasterTitle,
				ISNULL(AIS.ConvertedMark,0) AS ConvertedMark,
				ISNULL(AIS.GradeIndicator,'') AS Indicator,
				ISNULL(AIS.DescriptiveIndicator,'')  AS DescriptiveIndicator	,
				CM.Id AS ClassId,
				CM.Title AS ClassTitle,
				DM.Id AS DivisionId,
				DM.Title AS DivisionTitle,
				SA.Code AS Code,
				(SELECT DisplayTitle FROM sAssessment.tExamMaster WHERE Id = @rExamId) AS ExamTitle	,
				(CASE EM.IsDisplayPhoto WHEN 1 THEN
		        SI.StudentPhoto
			    ELSE NULL END)AS StudentPhoto,
				EM.IsDisplayPhoto,
				EM.IsOnPrePrinted,
				ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
				(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
				OI.MarksheetHeaderA4 
				ELSE 
				NULL END) AS MarksheetHeaderA4,
				ISNULL(AIS.ObtianMark,0) AS ObtianMark
								 
			FROM sStudent.vStudentAcademic SA
				INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1
				INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
				INNER JOIN sAssessment.tCCECSGroupMaster CCEM ON CCEM.Id=AM.CCECAGroupId
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId AND SA.OrgId = CM.OrgId
				INNER JOIN sSetup.tDivisionmaster DM ON DM.Id = SA.DivisionId AND SA.OrgId = DM.OrgId
				LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND CCECSId= AM.Id And AIS.ExamId=@rExamId
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = AIS.ExamId
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
				LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			WHERE
				 SA.ClassId=@rClassId 
				And SA.DivisionId =@rDivisionID	
				And SA.BatchId =@rBatchId
				AND AIS.ExamId=@rExamId
				and ((AM.CCECAGroupId=@rCCECAGroupId) OR (@rCCECAGroupId=0))
				AND((AM.Id=@rCCEMasterId) OR (@rCCEMasterId=0))	
				and AM.OrgId=@rOrgId
				and ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
						
			--FROM   
			--	sAssessment.tCCECSMaster CM 
			--	INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id=CM.CCECAGroupId AND CM.OrgId=@rOrgId
			--	INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CGM.Id				
			--	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CL.ClassId 
			--	LEFT JOIN   sAssessment.tCCECSExamScore CC  ON CC.CCECSID=CM.ID  
			--	AND CC.AcademicId = SA.AcademicId AND ExamId=@rExamId	AND CC.AcademicId = @rAcademicId	
			--	WHERE ((SA.AcademicId = @rAcademicId) OR (@rAcademicId=0))
			--		and SA.ClassId=@rClassId and SA.DivisionId=@rDivisionId
		
			 ORDER BY SA.RollNo
			
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END
GO
PRINT N'Altering 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
	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].[pRptSubjectActivityExamMarkGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamMarkGet]
	  
	   @rOrgId int
	  ,@rExamId int,
	  @rClass int,
	  @rDivisionId int,
	  @rBatchId int,
	  @rActivityId int,
	  @rSubjectSubActivityId int,
	  @rBuilder1 nvarchar(max)
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

	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
 
			SELECT 		 
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.Marks,0) AS Marks,
				 
				 SAM.Title AS SubjectActivityTitle,
				 SSA.Title AS SubjectSubActivityTitle,
				 SAM.Id AS ActivityId,
				 SSA.Id AS SubjectSubActivityId,
				 SAM.OrderIndex AS ActivityOrderIndex,
				 SSA.OrderIndex AS SubjectSubActivityOrderIndex,
				 SM.Title AS SubjectName,
				 SAM.ClassSubjectId,
				 ISNULL(AIS.Grade,'') AS Grade,
				 ISNULL(AIS.GradeIndicator,'') AS GradeIndicator,
				 ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
				 (SELECT EM.FirstName + ' ' + EM.LastName  From sHrm.tEmployeeMaster EM 
				  INNER JOIN sSetup.tDivisionMaster DM ON EM.Id = DM.InchargeEmployeeId Where DM.Id = @rDivisionId) AS ClassTeacher,
				  ISNULL(SR.TotalDays,0)AS TotalDays,
				  ISNULL(SR.PresentDays,0)AS PresentDays,
				  CONVERT(bit,@lDecimalConfig) AS IsDecimal,
				  ISNULL(SR.GeneralRemark,'') AS GeneralRemark,
				  ISNULL(SR.Achievements,'') AS Achievements,
				  ISNULL(SR.ResultRemark1,'') AS ResultRemark1,
				  ISNULL(SR.ResultRemark2,'') AS ResultRemark2,
				  ISNULL(SR.ResultRemark3,'') AS ResultRemark3
					 
			FROM 
			  sAssessment.tCCESubjectActivityMaster SAM 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
			INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId		
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
			LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id And AIS.ExamId=@rExamId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId AND SR.ExamId = @rExamId -- Mantis : 0027635

	    	 WHERE
				 ((SAM.ClassSubjectId=@rClass) OR (@rClass=0))
				And SA.DivisionId =@rDivisionID	
				And SA.BatchId =@rBatchId
				--AND AIS.ExamId=@rExamId
				and ((SSA.SubjectActivityId=@rActivityId) OR (@rActivityId=0))
				AND((SSA.Id=@rSubjectSubActivityId) OR (@rSubjectSubActivityId=0))	
				and SSA.OrgId=@rOrgId
				AND  SA.StatusId = 1		
		 
			 ORDER BY SA.RollNo
			
END
GO
PRINT N'Altering Procedure [sAttendance].[pStudentAttendaceDashboardGet]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

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

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

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

--Organization wise Attendance

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

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

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

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

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

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

      END
   
ELSE IF @rTypeId=24     
      BEGIN

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

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

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

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

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

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

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


GO
ALTER PROCEDURE [sFee].[pCollectionGroupGet]
		
	@rSourceId bigint,
	@rSourceTypeId int=0,
	@rReceiptBookId int=0,
	@rReceiptId bigint=0,
	@rBatchId int,
	@rCollectionGroupId int =0 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	DECLARE @lClassId int
	DECLARE @lAdmissionCategoryId int,@lOrgId int,@lOrgGorupId int
	SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId,@lOrgId = OrgId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId	
	
	Select @lOrgGorupId = OrgGroupId from sSetup.tOrganizationMaster Where Id = @lOrgId
				
	DECLARE @lConfigValue nvarchar(50)
	--,@lOrgGroupBatchId int
	--SELECT @lOrgGroupBatchId = OrgGroupBatchId FROM [sSetup].[tBatchMaster] WHERE Id = @rBatchId
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 487 AND SourceTypeId = 2010 AND SourceId = @lOrgGorupId


	IF(@lConfigValue = 'True')
	BEGIN
		SELECT 
			SUM(CG.PayableAmount) AS PendingAmount 
			,CollectionGroupId
			,StartDate
			,EndDate
			,CollectionGroupName
			,ReceiptBookId
			,ReceiptBook
			,CollectionGroupCode -- added for mantis 0026962 by Foram
		FROM
			(SELECT 
				FM.Id AS FeeId,
				FM.Title AS FeeName,
				FS.Id AS FeeSetupId,			 
				FS.ReceiptBookId,
				RBM.Title AS ReceiptBook,
				ISNULL(R.PaidAmount,0) AS PaidAmount,
				ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.DiscountAmount,0) -  ISNULL(FA.NotApplicableAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0)AS PayableAmount,
				--FM.OrderIndex,
				FS.CollectionGroupId,
				CGM.StartDate,
				CGM.EndDate,
				CGM.Title AS CollectionGroupName,
				CGM.OrderIndex,
				CGM.Code AS CollectionGroupCode -- added for mantis 0026962 by Foram
			FROM 
				sFee.tFeeMaster FM
				INNER JOIN 
				(
					SELECT 
						FS1.FeeId,
						FS1.Id,
						ISNULL(FS1.IsOptional,0)AS IsOptional,
						ISNULL(FS1.IsVariable,0)AS IsVariable,
						ISNULL(FS1.Amount,0)AS Amount,
						ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
						ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
						FS1.BatchId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
					WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @rBatchId  
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
						AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				
						UNION ALL
				
					SELECT 
						FS1.FeeId,
						FS1.Id,
						ISNULL(FS1.IsOptional,0)AS IsOptional,
						ISNULL(FS1.IsVariable,0)AS IsVariable,
						ISNULL(FS1.Amount,0)AS Amount,
						ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
						ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
						FS1.BatchId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO
					ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
				WHERE
						FS1.ClassId=@lClassId AND FS1.BatchId =@rBatchId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				
				) FS ON FS.FeeId=FM.Id
				INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId
				INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
				LEFT JOIN
				(
					SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId FROM
					sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 	
					INNER JOIN sFee.tFeeSetup FSR ON FSR.Id = RD.FeeSetupId 	
					WHERE						
					(R.ReceiptBookId = @rReceiptBookId	OR @rReceiptBookId = 0)	
					AND ((FSR.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
					AND R.SourceId= @rSourceId
					AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
					AND R.IsObsolete = 0 			 
					 GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id 
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
			where 
				((FS.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
				AND (((ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.NotApplicableAmount,0) -  ISNULL(FA.DiscountAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0))>0) AND(@rReceiptId=0) OR(@rReceiptId<>0))
				AND(FS.BatchId=@rBatchId)
				AND CAST(sCommon.fGetDate() AS DATE) <= CAST(CGM.EndDate AS DATE)
				AND CGM.IsObsolete = 0
			) AS CG
		GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,CollectionGroupCode,OrderIndex,ReceiptBookId,ReceiptBook
		ORDER BY CG.StartDate,CG.OrderIndex
	END
	ELSE
	BEGIN
		SELECT 
			SUM(CG.PayableAmount) AS PendingAmount 
			,CollectionGroupId
			,StartDate
			,EndDate
			,CollectionGroupName
			,ReceiptBookId
			,ReceiptBook
			,CollectionGroupCode -- added for mantis 0026962 by Foram
		FROM
			(SELECT 
				FM.Id AS FeeId,
				FM.Title AS FeeName,
				FS.Id AS FeeSetupId,			 
				FS.ReceiptBookId,
				RBM.Title AS ReceiptBook,
				ISNULL(R.PaidAmount,0) AS PaidAmount,
				ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.DiscountAmount,0) -  ISNULL(FA.NotApplicableAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0)AS PayableAmount,
				--FM.OrderIndex,
				FS.CollectionGroupId,
				CGM.StartDate,
				CGM.EndDate,
				CGM.Title AS CollectionGroupName,
				CGM.OrderIndex,
				CGM.Code AS CollectionGroupCode -- added for mantis 0026962 by Foram
			FROM 
				sFee.tFeeMaster FM
				INNER JOIN 
				(
					SELECT 
						FS1.FeeId,
						FS1.Id,
						ISNULL(FS1.IsOptional,0)AS IsOptional,
						ISNULL(FS1.IsVariable,0)AS IsVariable,
						ISNULL(FS1.Amount,0)AS Amount,
						ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
						ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
						FS1.BatchId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
						WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @rBatchId  
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
						AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				
					UNION ALL
				
					SELECT 
						FS1.FeeId,
						FS1.Id,
						ISNULL(FS1.IsOptional,0)AS IsOptional,
						ISNULL(FS1.IsVariable,0)AS IsVariable,
						ISNULL(FS1.Amount,0)AS Amount,
						ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
						ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
						FS1.BatchId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO
					ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
				WHERE
						FS1.ClassId=@lClassId AND FS1.BatchId =@rBatchId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				
				) FS ON FS.FeeId=FM.Id
				INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId
				INNER JOIN sFee.tReceiptBookMaster RBM
					ON RBM.Id=FS.ReceiptBookId
				LEFT JOIN
				(
					SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId FROM
					sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 	
					INNER JOIN sFee.tFeeSetup FSR ON FSR.Id = RD.FeeSetupId 	
					WHERE						
					 (R.ReceiptBookId = @rReceiptBookId	OR @rReceiptBookId = 0)	
					 AND ((FSR.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
					AND R.SourceId= @rSourceId
					AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
					AND R.IsObsolete = 0 			 
					 GROUP BY FeeSetupId
		
				) R ON R.FeeSetupId = FS.Id 
				LEFT JOIN sFee.tFeeAllocation FA
					ON FA.FeeSetupId=FS.Id AND 
					(FA.SourceId=@rSourceId) AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
			where 
				((FS.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
				AND (((ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.NotApplicableAmount,0) -  ISNULL(FA.DiscountAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0))>0) AND(@rReceiptId=0) OR(@rReceiptId<>0))
				AND(FS.BatchId=@rBatchId)
				AND CGM.IsObsolete = 0
		  ) AS CG
		GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,CollectionGroupCode,OrderIndex,ReceiptBookId,ReceiptBook
		ORDER BY CG.StartDate,CG.OrderIndex
	END
END
GO
PRINT N'Altering Procedure [sFee].[pFeeSetupFeeWiseRemove]...';


GO
ALTER PROCEDURE [sFee].[pFeeSetupFeeWiseRemove]

	 @rId int,
	 @rFeeId int,
	 @rAdmissionCategoryId int,
	 @rBatchId int,
	 @rCheck bit
	
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 IF(@rCheck=1)
	 BEGIN 

		If Exists(select FeeSetupId from sFee.tFeeAllocation where FeeSetupId=@rId)
	    BEGIN
			select -50 as Result
			RETURN
		END		
		else If Exists(select FeeSetupId from sFee.tReceiptDetail where FeeSetupId=@rId)
	    BEGIN
			select -51 as Result
			RETURN
		END 
		else If Exists(select FeeSetupId from sFee.tFeeOptional where FeeSetupId=@rId)
	    BEGIN
			select -52 as Result
			RETURN
		END 
		-- Removed for mantis : 0028005 By Foram
		--If Exists(select FeeSetupId from sFee.tFeeAllocationStudent where FeeSetupId=@rId)
		--BEGIN
		--	select -50 as Result
		--	RETURN
		--END 
		select 0 as Result	
		END	
		ELSE
		BEGIN
		
		BEGIN TRY
		BEGIN TRANSACTION	
			ALTER TABLE sfee.tReceiptDetail 
			 WITH CHECK CHECK CONSTRAINT FK_sFee_tReceiptDetail_FeeSetupId

			ALTER TABLE sFee.tFeeOptional 
			 WITH CHECK CHECK CONSTRAINT FK_sFee_tFeeOptional_tFeeSetupId 

			ALTER TABLE sFee.tFeeAllocation 
			 WITH CHECK CHECK CONSTRAINT FK_sFee_tFeeAllocation_FeeSetupId

			Delete From sFee.tFeeSetup where FeeId=@rFeeId AND AdmissionCategoryId=@rAdmissionCategoryId AND BatchId=@rBatchId AND ((Id=@rId)OR(@rId=0))

		COMMIT TRANSACTION	
		END TRY
		BEGIN CATCH 
			ROLLBACK TRANSACTION
			SELECT -1 AS Result
		END CATCH	
		SELECT 11 AS Result
END	
	
	
		

	
	

END
GO
PRINT N'Altering Procedure [sFee].[pPendingFeeDashboardGet]...';


GO
ALTER PROCEDURE [sFee].[pPendingFeeDashboardGet]

		@rOrgGroupBatchId int = 0,
		@rCommonOrgGroupBatchId int = 0,
		@rType int,
		@rFilterType nvarchar(Max),
		@rFeeType nvarchar(Max),
		@rStudentStatus int = 0,
		@rUptoDate date = '',
		@rDepartmentId int=0,
	    @rOrgId int,
		@rReceiptBookId int,
		@rOrgGroupId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT @rOrgGroupBatchId = Id FROM sSetup.tOrgGroupBatchMaster WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId

IF (@rType = 1)
 BEGIN
IF(@rFilterType = 'Organizationwise')		
	BEGIN 
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		--SELECT
		--	SA.OrgId,
		--	O.Title AS OrgName,
		--	SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
		--	FHM.Id AS FeeHeadId,
		--	FHM.Title AS FeeHeadName,
		--	FHM.OrderIndex
		--FROM
		--	sStudent.vStudentAcademic SA
		--	INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		--	INNER JOIN 
		--	(
		--		SELECT 
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			FM.Title AS FeeName,
		--			FM.FeeHeadId,
		--			SA1.Id As AcademicId,
		--			FS1.Id,
		--			FS1.StartDate
 	--			FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		--		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
		--		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		--		WHERE 
		--			BM.OrgGroupBatchId = @rOrgGroupBatchId
		--			AND (FS1.IsOptional=0)
		--			-- IsInContext
		--			AND BM.IsInContext = 1
		--		UNION ALL
		--		SELECT 
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			FM.Title AS FeeName,
		--			FM.FeeHeadId,
		--			SA1.AcademicId As AcademicId,
		--			FS1.Id,
		--			FS1.StartDate
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		--		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		--		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		--		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		--		WHERE
		--				SA1.OrgGroupBatchId = @rOrgGroupBatchId
		--				AND (FS1.IsOptional=1)
		--				-- IsInContext
		--				AND BM.IsInContext = 1
		--		) FS ON FS.AcademicId=SA.AcademicId
		--		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		--		LEFT JOIN
		--		(
		--			SELECT 
		--			    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--			FROM
		--				sFee.tReceipt R 
		--				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
		--				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
		--			WHERE		
		--				(R.SourceTypeId = 2001)
		--				AND (R.IsObsolete = 0) 
		--				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
		--				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
		--				AND (R.ReceiptDate <= @rUptoDate) 
		--				-- IsInContext
		--				AND BM.IsInContext = 1 
		--				GROUP BY FeeSetupId,R.SourceId
		--		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		--		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--	WHERE
		--	  SA.OrgGroupBatchId = @rOrgGroupBatchId
		--	  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
		--	  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		--	  -- IsInContext
		--	  AND BM.IsInContext = 1
		--	GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex
		--	ORDER BY OrgId,FHM.OrderIndex

		CREATE TABLE #FeeHeadwisetmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		--ReceiptBookId int 
		)

		INSERT INTO #FeeHeadwisetmp
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN #FeeHeadwisetmp FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
					sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
					AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
					AND (R.ReceiptDate <= @rUptoDate) 
					-- IsInContext
					AND BM.IsInContext = 1 
					GROUP BY FeeSetupId,R.SourceId
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,FHM.OrderIndex

		DROP TABLE #FeeHeadwisetmp
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		CREATE TABLE #FeeMasterwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			OrderIndex int
		)
	 
	 INSERT INTO #FeeMasterwisetmp
		 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
 		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #FeeMasterwisetmp FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
				SA.OrgGroupBatchId = @rOrgGroupBatchId
				AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
				AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				-- IsInContext
				AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FS.FeeId,FS.FeeName,FS.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,FS.FeeId
	 DROP TABLE #FeeMasterwisetmp
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		CREATE TABLE #CollectionGroupwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			CollectionGroupId int
		)
	 INSERT INTO #CollectionGroupwisetmp
	 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
 		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN #CollectionGroupwisetmp FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,CGM.Id,CGM.Title,CGM.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,CGM.Id

	 DROP TABLE #CollectionGroupwisetmp
	 END
	END
ELSE IF(@rFilterType = 'Departmentwise')
	BEGIN
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartFeeHeadWise') IS NOT NULL DROP TABLE #tmpDepartFeeHeadWise
		CREATE TABLE #tmpDepartFeeHeadWise
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		)

		Insert Into #tmpDepartFeeHeadWise
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
		INNER JOIN #tmpDepartFeeHeadWise FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
			SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
			FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (R.ReceiptDate <= @rUptoDate)
				-- IsInContext
				AND BM.IsInContext = 1  
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1 
		GROUP BY SA.DepartmentId,SA.DepartmentName,FHM.Id,FHM.Title,FHM.OrderIndex,DM.OrderIndex
		ORDER BY DM.OrderIndex,DepartmentId,FHM.Id
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN

		IF OBJECT_ID('tempdb..#tmpDepartFeeMasterwise') IS NOT NULL DROP TABLE #tmpDepartFeeMasterwise
		CREATE TABLE #tmpDepartFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		OrderIndex int
		)

		Insert Into #tmpDepartFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1


		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN #tmpDepartFeeMasterwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,FS.FeeId,FS.FeeName,FS.OrderIndex,DM.OrderIndex
			ORDER BY DM.OrderIndex,DepartmentId,FS.FeeId
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartCollectionGroupwise') IS NOT NULL DROP TABLE #tmpDepartCollectionGroupwise
		CREATE TABLE #tmpDepartCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int
		)

		INSERT INTO #tmpDepartCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1


		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN #tmpDepartCollectionGroupwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,CGM.Id,CGM.Title,CGM.OrderIndex,DM.OrderIndex
			ORDER BY DM.OrderIndex,DepartmentId,CGM.Id
	 END
	END
ELSE IF(@rFilterType = 'ReceiptBookwise')
	BEGIN
	IF(@rFeeType = 'FeeHeadwise')
	BEGIN
		-- For Timeout issue
		CREATE TABLE #tmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int 
		)

		INSERT INTO #tmp
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
 		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1



	 SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.tAcademic SA
			INNER JOIN [sStudent].[tStudentMaster] SM ON SA.StudentId = SM.Id 
			INNER JOIN [sSetup].[tBatchMaster] BM ON SA.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			--INNER JOIN 
			--(
				--SELECT 
				--	ISNULL(FS1.Amount,0)AS Amount,
				--	FM.Title AS FeeName,
				--	FM.FeeHeadId,
				--	SA1.Id As AcademicId,
				--	FS1.Id,
				--	FS1.StartDate,
				--	FS1.ReceiptBookId
 			--	FROM sFee.tFeeSetup FS1
				--INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				--INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				--AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				--INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				--WHERE 
				--	BM.OrgGroupBatchId = @rOrgGroupBatchId
				--	AND (FS1.IsOptional=0)
				--	-- IsInContext
				--	AND BM.IsInContext = 1
				--UNION ALL
				--SELECT 
				--	ISNULL(FS1.Amount,0)AS Amount,
				--	FM.Title AS FeeName,
				--	FM.FeeHeadId,
				--	SA1.AcademicId As AcademicId,
				--	FS1.Id,
				--	FS1.StartDate,
				--	FS1.ReceiptBookId
				--FROM sFee.tFeeSetup FS1
				--INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				--AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				--INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				--WHERE
				--		SA1.OrgGroupBatchId = @rOrgGroupBatchId
				--		AND (FS1.IsOptional=1)
				--		-- IsInContext
				--		AND BM.IsInContext = 1
				--) 
				INNER JOIN #tmp FS ON FS.AcademicId=SA.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			WHERE
			  BM.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SM.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FHM.Id,FHM.Title,FHM.OrderIndex,RBM.OrderIndex
			ORDER BY RBM.OrderIndex,ReceiptBookId,FHM.Id

		DROP TABLE #tmp
	 END
	ELSE IF(@rFeeType = 'FeeMasterwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptFeeMasterwise') IS NOT NULL DROP TABLE #tmpReceiptFeeMasterwise
		CREATE TABLE #tmpReceiptFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int,
		OrderIndex int
		)

		INSERT INTO  #tmpReceiptFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptFeeMasterwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FS.FeeId,FS.FeeName,FS.OrderIndex,RBM.OrderIndex
			ORDER BY RBM.OrderIndex,ReceiptBookId,FS.FeeId
	END
	ELSE IF(@rFeeType = 'CollectionGroupwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptCollectionGroupwise') IS NOT NULL DROP TABLE #tmpReceiptCollectionGroupwise
		CREATE TABLE #tmpReceiptCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int,
		ReceiptBookId int
		)

		INSERT INTO #tmpReceiptCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptCollectionGroupwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,CGM.Id,CGM.Title,CGM.OrderIndex,RBM.OrderIndex
			--ORDER BY ReceiptBookId,CGM.Id
			ORDER BY RBM.OrderIndex,CGM.OrderIndex
	END
	END 
  END
ELSE IF(@rType = 2)
		BEGIN

			IF OBJECT_ID('tempdb..#tmptbl') IS NOT NULL DROP TABLE #tmptbl
			CREATE TABLE #tmptbl
			(
				FeeId int,
				Id int,
				IsOptional bit,
				IsVariable bit,
				Amount decimal (12,2),
				StartDate date,
				EndDate date,
				BatchId int,
				ReceiptBookId int,
				AcademicId bigint,
				FeeName nvarchar(100),
				FeeHeadId int,
				CollectionGroupId int,
				FeeOrderIndex int
			)
			INSERT INTO #tmptbl 
			SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							SA1.Id AS AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 
						FROM sFee.tFeeSetup FS1
						INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
						INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
						AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
						INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE 
							BM.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=0)
							-- IsInContext
							AND BM.IsInContext = 1
						UNION ALL
				
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							SA1.AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 			 
						FROM sFee.tFeeSetup FS1
						INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
						INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE
							SA1.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=1)
							-- IsInContext
							AND BM.IsInContext = 1
	
				SELECT 
					SA.OrgId,
					SA.OrganizationName as OrgName,
					SA.ClassId,
					SA.ClassName,
					SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount
				FROM 
					sStudent.vStudentAcademic SA
					INNER JOIN #tmptbl  FS ON FS.AcademicId=SA.AcademicId
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
					LEFT JOIN
					(
						SELECT 
								ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
						FROM
							sFee.tReceipt R 
							INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
							INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
							INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
							INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
							 
						WHERE		
							(R.SourceTypeId = 2001)
							AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND (R.IsObsolete = 0) 
							AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
							AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
							AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016
							-- IsInContext
							AND BM.IsInContext = 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
					 LEFT JOIN sFee.tCollectionGroupMaster CGM
						ON FS.CollectionGroupId=CGM.Id	
					 LEFT JOIN sStudent.tStudentCommunication SC 
						ON SC.StudentId = SA.StudentId
					 LEFT JOIN sStudent.tStudentOther SO 
						ON SO.StudentId = SA.StudentId
					 INNER JOIN sFee.tFeeHeadMaster FHM
						ON FHM.Id = FS.FeeHeadId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id	
				  LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
				  LEFT JOIN
					(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
					ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
				WHERE	
				 SA.OrgGroupBatchId = @rOrgGroupBatchId
                 AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
                 AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				 AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
				 -- IsInContext
				 AND BM.IsInContext = 1
				GROUP BY 
						SA.ClassId,SA.ClassName,SA.OrgId,SA.OrganizationName
				Order By
						SA.ClassId
		END
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptAdd]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

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

	 IF @lConfigValue = ''
		SET @lConfigValue = 'ReceiptBookWise'

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

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
--IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
--			BEGIN
--				SELECT -102 AS Result
--				RETURN	
--			END

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

	Declare @lSourceTypeId int 
	SET @lSourceTypeId =(select ISNULL(SourceTypeId,0) from sSecurity.tUser where Id = @rCreatedUserId)

	DECLARE @lCreatedUserId bigint
	IF(@lSourceTypeId = 2001 OR @lSourceTypeId = 2003 OR @rCreatedUserId = 3)
		SET @lCreatedUserId=(Select [sCommon].[fGetBigIntIdForOrg](4,LEFT(@rOrgGroupBatchId,4)))
	ELSE
		SET @lCreatedUserId = @rCreatedUserId 

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

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

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


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
						
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date='',
			@rClassId int = 0,
			@rOrgIds nvarchar(max) = '',
			@rReceiptPrintGroupId nvarchar(100)='',
			@rDivisionId int = 0,
			@rAdmissionCategoryId int = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	Declare @lIDConfigValue nvarchar(50)='',@lOrgGroup_Id int=0
	Select @lOrgGroup_Id = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	 
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @rReceiptId

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

	IF(@rOrgGroupId=0) SET @rOrgGroupId=@lOrgGroupId

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,			
			SA.AcademicId,
			--SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,			
			--changes by Jash on 06/11/2020--%
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),ISNULL(FR.PaymentTransactionId,''))  END AS ChequeNo,
			--CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo
			--	WHEN ISNULL(PT.BankTransactionId,'') = '' THEN  CONVERT(nvarchar(20),FR.PaymentTransactionId)
			--	ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) +' - '+ CONVERT(nvarchar(20),PT.BankTransactionId) END AS ChequeNo,
			--%ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,					
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN '' 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,			
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			(CASE WHEN  ISNULL(FR.PaymentTransactionId,0) > 0 
			  THEN -- Navrachana
				'Online Generated'
				ELSE ISNULL(U.DisplayTitle,'') END) AS UserName,
			--ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0 THEN 
			--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	 			  
			(CASE WHEN  RBM.ReportId = 20576
			      THEN -- HM patel report
				  [sFee].[fReceiptMonthDetailGet](FR.ID,0)
			      WHEN RBM.ReportId = 30457 
			      THEN
				  [sFee].[fReceiptMonthDetailGet](FR.ID,1)		
			      WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
				  [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Head wise Month name in detail
				  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN				
				  [sFee].[fFeeMonthNameGet](FR.ID,FM.Id) -- Fee wise Month name in detail
			ELSE '' END) 
			AS MonthDetail,    			
			(CASE WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
					 Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
					sFee.tReceipt FR1				
					INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
					INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
					INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
					INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
					Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					Order By FS1.StartDate
					FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' )    -- Fee Head wise Fee Duration
				  WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN
					FS.FeeDuration -- Fee wise Fee Duration
				 ELSE '' END) AS FeeDuration,			
			--Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
			--sFee.tReceipt FR1				
			--INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
			--INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
			--INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
			--INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
			--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
			----Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			-- Order By FS.StartDate
			--FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' ) AS FeeDuration,			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN  FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN  FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
			ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue ,
	        SF.FatherName,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,
			(ISNULL((CASE WHEN SC.PresentStreetOne IS NOT NULL AND SC.PresentStreetOne!='' THEN ''+ SC.PresentStreetOne END),'')+
			ISNULL((CASE WHEN SC.PresentStreetTwo IS NOT NULL AND SC.PresentStreetTwo!=''  THEN ', '+ SC.PresentStreetTwo END),'')+
			ISNULL((CASE WHEN SC.PresentStreetThree IS NOT NULL AND SC.PresentStreetThree!=''  THEN ', '+ SC.PresentStreetThree END),'')+
			ISNULL((CASE WHEN SC.PresentCity IS NOT NULL AND SC.PresentCity!=''  THEN ', ' + SC.PresentCity  END),'')+
			ISNULL((CASE WHEN SC.PresentState IS NOT NULL AND SC.PresentState!=''  THEN  ', '+ SC.PresentState END),'')+
			ISNULL((CASE WHEN SC.PresentZipCode IS NOT NULL AND SC.PresentZipCode!=''  THEN  ', '+ SC.PresentZipCode  END),''))
			 AS PresentAdress,
			--ISNULL(SC.PresentStreetOne +','+ SC.PresentStreetTwo +','+ SC.PresentStreetThree +','+ SC.PresentCity +','+ SC.PresentState +'-'+ SC.PresentZipCode ,'') AS PresentAdress,
			SC.ParentContactNo,			
			ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount,
			CASE WHEN @rOrgGroupId = 1134 OR @rOrgGroupId = 1742 THEN
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,RBM.Id),0) END)
			ELSE 
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,0),0) END) END AS PendingFeeAmount,
			SA.FirstName,
			SA.LastName,
			ISNULL([sFee].[fFeeAmountSumGet](FR.SourceId),0) AS FeeAmount,
			ISNULL([sFee].[fFeeReceiptDiscountSumGet](FR.SourceId),0) AS ExemptionAmountSum,
			[sFee].[fTransportBusRouteGet](SA.StudentId,FR.OrgGroupBatchId) AS TransportBusRoute,
			ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
			ISNULL(FHM.Number,0) AS FeeHeadNumber,
			ISNULL(FM.Number,0) AS FeeNumber,
			ISNULL(RBM.DigitalSignature,0x) AS DigitalSignature,
			ISNULL(FR.CancelStatusRemark,'') AS CancelStatusRemark,
			FS.Amount AS FeeSetupAmount,
			FR.CreatedDateTime ,
			ISNULL(FR.PaymentTransactionId,0) As PaymentTransactionId,
			SA.MiddleName,
			CONVERT(char(5),FR.CreatedDateTime,108) AS CreatedTime,
			--by megha - 0026430
			(CASE WHEN ISNULL(FA.VariableAmount,0) > 0 Then FA.VariableAmount 
			      When ISNULL(FS.Amount,0) > 0 Then FS.Amount END) + ISNULL(FA.AdditionalAmount,0) - ISNULL(FA.DiscountAmount,0) - ISNULL(FA.NotApplicableAmount,0) As TotalPayableAmount
			 
 	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
			AND ((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0) )
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
END

--BEGIN
--SELECT
-- CAST(0 AS bigint) AS ReceiptId,
-- 0	AS ReceiptNumber,
-- CAST('' AS date) AS ReceiptDate,
-- CAST(0 AS bigint) AS AcademicId,
-- ''	AS Name,
--''	AS Code,
-- 0	AS RollNo,
--0	AS ClassId,
--0	AS DivisionId,
--''	AS ClassName,
--''	AS DivisionName,
--''	AS ClassDivision,
--0	AS FeeHeadId,
--''	AS FeeHead,
--0	AS FeeId,
--''	AS FeeName,
--CAST(0.0 AS decimal(12,2)) AS PaidAmount,
--CAST(0 AS tinyint) AS PayTypeId,
--''	AS PayType,
--''	AS ChequeNo,	
--''	AS BankName,
--''	AS Address1,
--''	AS Address2,
--''	AS FullTitle,
--CAST(0.0 AS decimal(12,2)) AS TotalReceiptAmount,
--CAST(0.0 AS decimal(12,2)) AS ReceiptAmount,					
--''	AS ReceiptAmountInWords,		
--CAST(0.0 AS decimal(12,2)) AS DiscountAmount,
--''	AS Remark,
--''	AS UserName,		
--0x  AS OrgLogo,
--''	AS Remark1,
--''	AS Remark2,			 
--CAST(0 AS bit) AS IsOnPrePrinted,
--CAST(0 AS bit) AS IsSupressLogo,
--CAST(0 AS bit) AS IsDisplaySchoolName,
--0	AS ReportId,
--''	AS OrganizationName,		  
--''	AS MonthDetail,    			
--''	AS FeeDuration,		
--''	AS DepartmentName,
-- 0	AS FeeOrderIndex,
--CAST(0 AS smallint)	AS FeeHeadOrderIndex,
--CAST(0 AS bit) AS IsCancelReceipt,
--''	AS CurrencyCode,
--''	AS CurrencyTitle,
--''	AS Batch,
--CAST('' AS date) AS ChequeDate,
--CAST(0 AS bit) AS IsMonthDetailOnly,
--CAST(0 AS bit) AS IsFeeInvoiceHeadwise,
--''	AS GroupTitle,
--CAST(0 AS bit) AS IsSuppressFeeDetail,
--''	AS CollectionGroupName,
--0	AS InvoiceNumber,
--''	AS SUID,
--CAST(0 AS tinyint) AS HeaderDisplayId,
--0x  AS ReceiptBookHeader,
--CAST(0.0 AS decimal(6,2)) AS ServiceTaxPercentage,
--CAST(0.0 AS decimal(12,2)) AS AmountAfterDiscount,
--CAST(0.0 AS decimal(5,2)) AS CGSTPercentage,
--CAST(0.0 AS decimal(5,2)) AS SGSTPercentage,
--CAST(0.0 AS decimal(12,2)) AS CGSTAmount,
--CAST(0.0 AS decimal(12,2))	AS SGSTAmount,
--''	AS GSTINNo,
--''	AS HSNSACCode,
--''	AS ItemValue ,
--''	AS FatherName,
--''	AS MotherName,
--CAST(0.0 AS decimal(12,2)) AS ExemptionAmount,
--''	AS ExemptionRemark,
--0x AS EmployeeSign,
--''	AS PresentCity,
--''	AS PresentAdress,
--''	AS ParentContactNo,	
--CAST(0 AS bit) AS IsDisplayPendingFeeAmount,
--CAST(0.0 AS decimal(12,0)) AS PendingFeeAmount,
--''	AS FirstName,
--''	AS LastName,
--CAST(0.0 AS decimal(12,0))	AS FeeAmount,
--CAST(0.0 AS decimal(12,0)) AS ExemptionAmountSum,
--''	AS TransportBusRoute,
--''	AS BankAccountNumber,
--0	AS FeeHeadNumber,
--0	AS FeeNumber,
--0x AS DigitalSignature,
--''	AS CancelStatusRemark,
--CAST(0.0 AS decimal(12,2))	AS FeeSetupAmount,
--''	AS CreatedDateTime ,
--CAST(0 AS bigint)	AS PaymentTransactionId,
--''	AS MiddleName,
--'' AS CreatedTime,
-- 0 AS TotalPayableAmount
--END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeReplacementDeleteAndTransfer]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeReplacementDeleteAndTransfer]
	 
        @rExistingEmployeeId BIGINT,
		@rNewEmployeeId BIGINT,
		@rTitle NVARCHAR(500)
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--IF OBJECT_ID('tempdb..#tmpSplitTable') IS NOT NULL DROP TABLE #tmpSplitTable

	--CREATE Table #tmpSplitTable
	--(
	--	Id NVARCHAR(150)
	--)

	--INSERT INTO #tmpSplitTable
	--SELECT CAST(item AS NVARCHAR(150)) AS Id FROM  sCommon.fnsplit(@rId,',')
	
	IF (@rTitle = 'Assign Teacher')
	BEGIN
		IF NOT EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rNewEmployeeId)
		begin
			INSERT INTO sTimetable.tAssignTeacher
			Select TimeTableSchemaId, @rNewEmployeeId from sTimetable.tAssignTeacher WHERE EmployeeId = @rExistingEmployeeId
			delete from sTimetable.tAssignTeacher where EmployeeId = @rExistingEmployeeId
		end		
	END

	IF (@rTitle = 'Teacher Subject Division')
	BEGIN
		INSERT INTO sAcademic.tTeacherSubject
		Select @rNewEmployeeId,SubjectId from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId 
		and SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		
		delete from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId
		
		Insert into sAcademic.tTeacherSubjectDivision 
		select @rNewEmployeeId, SubjectId, DivisionId,SubjectCordinatorEmployeeId 
		from sAcademic.tTeacherSubjectDivision 
		where SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		AND EmployeeId = @rExistingEmployeeId
		
		delete from sAcademic.tTeacherSubjectDivision where EmployeeId = @rExistingEmployeeId		
	END

	IF (@rTitle ='Time Table')
	BEGIN
		Update sTimetable.tTimeTable
		Set EmployeeId = @rNewEmployeeId from sTimetable.tTimeTable where EmployeeId  = @rExistingEmployeeId
		
		UPDATE sTimetable.tTeacherWorkLoad SET EmployeeId = @rNewEmployeeId WHERE EmployeeId = @rExistingEmployeeId 
	END
	
	IF (@rTitle ='User Access')
	BEGIN
		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		declare @lNewUserId bigint= (select Id from sSecurity.tUser where SourceId = @rNewEmployeeId AND SourceTypeId = 95)

		IF (@lNewUserId IS NULL)
		BEGIN
			Return
		END
		ELSE
		BEGIN
		Insert into sSecurity.tUserOrganization 
		select OrgId, @lNewUserId from sSecurity.tUserOrganization WHERE UserId=@lExistingUserId
		AND OrgId NOT in (select OrgId from sSecurity.tUserOrganization WHERE UserId=@lNewUserId)

		delete from sSecurity.tUserOrganization  WHERE UserId=@lExistingUserId

		INSERT INTO sSecurity.tUserAccess
		SELECT SourceTypeId, SourceId, @lNewUserId FROM sSecurity.tUserAccess WHERE UserId=@lExistingUserId
		AND SourceId not in (select SourceId from  sSecurity.tUserAccess WHERE UserId=@lNewUserId)

		delete from sSecurity.tUserAccess  WHERE UserId=@lExistingUserId
		END
	END

	IF (@rTitle ='Class Teacher')
	BEGIN
		Update sSetup.tDivisionMaster SET InchargeEmployeeId = @rNewEmployeeId where  InchargeEmployeeId = @rExistingEmployeeId
	END

	IF (@rTitle ='Lesson Plan')
	BEGIN
		Update sAcademic.tLessonPlan SET EmployeeId = @rNewEmployeeId where EmployeeId = @rExistingEmployeeId
	END

	--Drop Table #tmpSplitTable
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeReplacementGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeReplacementGet]
	 
        @rEmployeeId bigint
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Declare @lTeacherSubjectId bigint = 0 , @lTeacherDivisionId bigint = 0
	IF OBJECT_ID('tempdb..#tmpTable') IS NOT NULL DROP TABLE #tmpTable
	CREATE Table #tmpTable 
	(
		Id bigint IDENTITY,
		Title nvarchar(50)
	)

	IF EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Assign Teacher'
		)
	END


	set @lTeacherSubjectId = (select top 1 1 from sAcademic.tTeacherSubject where EmployeeId = @rEmployeeId)
	SET @lTeacherDivisionId = (select top 1 1 from sAcademic.tTeacherSubjectDivision where EmployeeId = @rEmployeeId)
	IF ((@lTeacherSubjectId = 1) OR (@lTeacherDivisionId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Teacher Subject Division'
		)
	END

	IF EXISTS (select top 1 1 from sTimetable.tTimeTable where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Time Table'
		)
	END
		
	declare @lUserId bigint= (select top 1 Id from sSecurity.tUser where SourceId = @rEmployeeId AND SourceTypeId = 95)
	declare @lUserOrganizationId int ,@lUserAccessId int
	SET @lUserOrganizationId = (SELECT Top 1 1 FROM sSecurity.tUserOrganization WHERE UserId=@lUserId)
	SET @lUserAccessId= (SELECT top 1 1 FROM sSecurity.tUserAccess WHERE UserId=@lUserId)
	IF ((@lUserOrganizationId = 1) OR (@lUserAccessId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'User Access'
		)
	END

	IF EXISTS (select top 1 1 from sSetup.tDivisionMaster where InchargeEmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Class Teacher'
		)
	END	

	IF EXISTS (select top 1 1 from sAcademic.tLessonPlan where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Lesson Plan'
		)
	END

	select * from #tmpTable order by Title

	Drop Table #tmpTable
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeReplacementTransfer]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeReplacementTransfer]
	 
        @rExistingEmployeeId BIGINT,
		@rNewEmployeeId BIGINT,
		@rTitle NVARCHAR(max),
		@rOrgId int
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--IF OBJECT_ID('tempdb..#tmpSplitTable') IS NOT NULL DROP TABLE #tmpSplitTable

	--CREATE Table #tmpSplitTable
	--(
	--	Id NVARCHAR(max)
	--)

	--INSERT INTO #tmpSplitTable
	--SELECT CAST(item AS NVARCHAR(max)) AS Id FROM  sCommon.fnsplit(@rId,',')

	IF (@rTitle = 'Assign Teacher')
	BEGIN
		IF NOT EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rNewEmployeeId)
		begin
			INSERT INTO sTimetable.tAssignTeacher
			Select TimeTableSchemaId, @rNewEmployeeId from sTimetable.tAssignTeacher WHERE EmployeeId = @rExistingEmployeeId
		end
	END

	IF (@rTitle = 'Teacher Subject Division')
	BEGIN
		
		INSERT INTO sAcademic.tTeacherSubject
		Select @rNewEmployeeId,SubjectId from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId 
		and SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		
		Insert into sAcademic.tTeacherSubjectDivision 
		select @rNewEmployeeId, SubjectId, DivisionId,SubjectCordinatorEmployeeId 
		from sAcademic.tTeacherSubjectDivision 
		where SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		AND EmployeeId = @rExistingEmployeeId
		
	END
	
	IF (@rTitle = 'User Access')
	BEGIN
		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		declare @lNewUserId bigint= (select Id from sSecurity.tUser where SourceId = @rNewEmployeeId AND SourceTypeId = 95)
		IF (@lNewUserId IS NULL)
		BEGIN
			Return
		END
		ELSE
		BEGIN
			Insert into sSecurity.tUserOrganization 
			select OrgId, @lNewUserId from sSecurity.tUserOrganization WHERE UserId=@lExistingUserId
			AND OrgId NOT in (select OrgId from sSecurity.tUserOrganization WHERE UserId=@lNewUserId)

			INSERT INTO sSecurity.tUserAccess
			SELECT SourceTypeId, SourceId, @lNewUserId FROM sSecurity.tUserAccess WHERE UserId=@lExistingUserId
			AND SourceId not in (select SourceId from  sSecurity.tUserAccess WHERE UserId=@lNewUserId)
		END
	END
	
	--IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Time Table')
	--BEGIN

	--	UPDATE sTimetable.tTimeTable 
	--	SET EmployeeId = @rNewEmployeeId 
	--	WHERE EmployeeId = @rExistingEmployeeId 

	--	UPDATE sTimetable.tTeacherWorkLoad 
	--	SET EmployeeId = @rNewEmployeeId WHERE EmployeeId = @rExistingEmployeeId 
	--END

	--IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Class Teacher')
	--BEGIN
	--	Update sSetup.tDivisionMaster SET InchargeEmployeeId = @rNewEmployeeId where  InchargeEmployeeId = @rExistingEmployeeId
	--END

	--Drop Table #tmpSplitTable
END
GO
PRINT N'Altering Procedure [sHrm].[pImportEmployees_Update_Dynamicly]...';


GO
ALTER proc [sHrm].[pImportEmployees_Update_Dynamicly] 
@rOrgId int,
@rCreatedUserId bigint,
@rCode varchar(200) = '',
@rShortName varchar(200) = '',
@rFirstName varchar(200) = '',
@rMiddleName varchar(200) = '',
@rLastName varchar(200) = '',
@rGender varchar(50) = '',
@rEmpType varchar(100) = '',
@rEmpGroup varchar(100) = '',
@rEmpGrade varchar(100) = '',
@rDepartment varchar(150) = '',
@rDesignation varchar(150) = '',
@rQualification varchar(150) = '',
@rDOB datetime = '',
@rDateOfJoining datetime = '',
@rReligion varchar(150) = '',
@rCompayPhoneNo varchar(15) = '',
@rExtensionNo varchar(15)='',
@rCompayMailId varchar(100)='',
@rPersonalEmailid varchar(100)='',
@rMobileNo varchar(50)='',
@rPresentStreetOne varchar(200)='',
@rPresentStreetTwo varchar(200)='',
@rPresentStreetThree varchar(200)='',
@rPresentCity varchar(100)='',
@rPresentZipCode varchar(15)='',
@rPresentState varchar(100)='',
@rPresentCountry varchar(100)='',
@rPresentContactNo varchar(50)='',
@rCastCategory varchar(50)='',
@rFamilyCast varchar(100)='',
@rAccountNumber varchar(100)='',
@rBankName varchar(100)='',
@rBranch varchar(100)=0,
@rEPFNumber varchar(100)=0,
@rPanNumber  varchar(100)='',
@rAdhaarNumber varchar(100)='',
@rValidate varchar(250)='' ,
@rOrgGroupId int,
@rIdentificationMark1  varchar(200)='',
@rUIDNumber varchar(50)='',
@rDateOfLeaving datetime = '',
@rReason varchar(200)='',
@rBloodGroup varchar(50)='',
@rNumber Bigint,
@rProbationUptoDate date = '',
@rAhdocUptoDate date = '',
@rPermanentDate date = '',
@rDateOfResignation date = '',
@rWhatsAppContactNo nvarchar(20) = ''

as
begin	

	IF(@rDateOfLeaving='') 
	SET @rDateOfLeaving = NULL
	IF(@rDOB='') 
	SET @rDOB = NULL
	IF(@rDateOfJoining='') 
	SET @rDateOfJoining = NULL
	IF(@rProbationUptoDate='')
	SET @rProbationUptoDate = NULL
	IF(@rAhdocUptoDate='')
	SET @rAhdocUptoDate = NULL
	IF(@rPermanentDate='')
	SET @rPermanentDate = NULL
	IF(@rDateOfResignation='')
	SET @rDateOfResignation = NULL
	
	declare @EmpId bigint = 0
	select @EmpId = Id from sHrm.tEmployeeMaster where Code = @rCode and OrgID = @rOrgId AND ISNULL(IsOtherUser,0) = 0
	select @EmpId = isnull(@EmpId,0)
	
	declare @genderid int,@emptypeid int,@cmpanyid int,@departmenttid int,@designationid int, 
	 @employeegradeid int,@empgroupid int,@religionId int,@castcatagoryId 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 @emptypeid = isnull(Id,0) from sHrm.tEmployeeTypeMaster where Title = @rEmpType and OrgId = @rOrgId
 
	select @empgroupid = isnull(Id,0) from sHrm.tEmployeeGroupMaster where Title = @rEmpGroup
	
	select @employeegradeid = isnull(Id,0) from sHrm.tEmployeeGradeMaster where Title = @rEmpGrade and OrgId = @rOrgId
	 
	 select @departmenttid = isnull(Id,0) from sSetup.tDepartmentMaster where Title = @rDepartment and OrgId = @rOrgId
	 
	  select @bloodgroupid = isnull(Id,0) from sCommon.tBloodGroupMaster where Title = @rBloodGroup 
	
	if (isnull(@rDesignation,'') <> '')
	select @designationid =  isnull(Id,0) from sHrm.tEmployeeDesignationMaster where Title = @rDesignation and OrgId = @rOrgId
	else
	select @designationid = 0
	
	 if (isnull(@rReligion,'') <> '')
			select @religionId =  isnull(Id,0) from sCommon.tReligionMaster where Title = @rReligion and OrgGroupId = @rOrgGroupId
	else
			select @religionId = 0
	
	 if (isnull(@rCastCategory,'') <> '')
	 select @castcatagoryId =  isnull(Id,0) from sCommon.tCastCategoryMaster where Title = @rCastCategory and OrgGroupId = @rOrgGroupId
	 else
	select @castcatagoryId = 0
			
	select @genderid = isnull(@genderid,0),@emptypeid = isnull(@emptypeid,0),@empgroupid = isnull(@empgroupid,0),
	@employeegradeid = isnull(@employeegradeid,0),@departmenttid = isnull(@departmenttid,0),@designationid = isnull(@designationid,0),
	@religionId = isnull(@religionId,0),@castcatagoryId = isnull(@castcatagoryId,0) 
	
	declare @lNextNumber bigint,@Title varchar(100)=''
	
	if @rEmpGroup = ''
	begin
		
		if exists (select 1 from sHrm.tEmployeeGroupMaster where  Title = @Title)
		begin
			select @empgroupid = Id from sHrm.tEmployeeGroupMaster where Title = @Title
		end
		
	end
	
	 
	
	if @rEmpType = ''
	begin		
		
		if exists (select 1 from sHrm.tEmployeeTypeMaster where OrgId = @rOrgId and Title = @Title)
		begin
			select @emptypeid = Id from sHrm.tEmployeeTypeMaster where OrgId = @rOrgId and Title = @Title
		end
	end
	
	 
	if @rEmpGrade = ''
	begin
		 
		if exists(select 1 from sHrm.tEmployeeGradeMaster where OrgId = @rOrgId and Title = @Title)
		begin
			select @employeegradeid = Id from sHrm.tEmployeeGradeMaster where OrgId = @rOrgId and Title = @Title
		end
	end
	
	
	if @rDepartment = ''
	begin		
		 
		if exists (select * from sSetup.tDepartmentMaster  where Title = @Title and OrgId = @rOrgId)
		begin
			select @departmenttid = Id from sSetup.tDepartmentMaster  where Title = @Title and OrgId = @rOrgId
		end
	end
		

	if @rDesignation = ''
	begin
		select @Title = Title from sHrm.tEmployeeDesignationMaster where Id = 1
		if exists (select * from sHrm.tEmployeeDesignationMaster where Title = @Title and OrgId = @rOrgId)
		begin
			select @designationid = Id from sHrm.tEmployeeDesignationMaster where Title = @Title and OrgId = @rOrgId			
		end
	end
	 
	 if @rCastCategory = ''
	begin
		
		if exists (select 1 from sCommon.tCastCategoryMaster where  Title = @Title and OrgGroupId=@rOrgGroupId)
		begin
			select @castcatagoryId = Id from sCommon.tCastCategoryMaster where Title = @Title and OrgGroupId=@rOrgGroupId
		end
		
	end
	
	 
	 if @rReligion = ''
	begin
		
		if exists (select 1 from sCommon.tReligionMaster where  Title = @Title and OrgGroupId=@rOrgGroupId)
		begin
			select @religionId = Id from sCommon.tReligionMaster where Title = @Title and OrgGroupId=@rOrgGroupId
		end
		
	end
	
	if @rShortName <> ''
	select @rShortName = [sSetup].[fPortalXMLTagsReplaceReverse](@rShortName)
	if @rFirstName <> ''
	select @rFirstName = [sSetup].[fPortalXMLTagsReplaceReverse](@rFirstName)
	if @rMiddleName <> ''
	select @rMiddleName = [sSetup].[fPortalXMLTagsReplaceReverse](@rMiddleName)
	if @rLastName <> ''
	select @rLastName = [sSetup].[fPortalXMLTagsReplaceReverse](@rLastName)
	if @rCompayPhoneNo <> ''
	select @rCompayPhoneNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rCompayPhoneNo)
	if @rExtensionNo <> ''
	select @rExtensionNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rExtensionNo)
	if @rCompayMailId <> ''
	select @rCompayMailId = [sSetup].[fPortalXMLTagsReplaceReverse](@rCompayMailId)
	if @rPersonalEmailid <> ''
	select @rPersonalEmailid = [sSetup].[fPortalXMLTagsReplaceReverse](@rPersonalEmailid)
	if @rMobileNo <> ''
	select @rMobileNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rMobileNo)
	if @rPresentStreetOne <> ''
	select @rPresentStreetOne = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetOne)
	if @rPresentStreetTwo <> ''
	select @rPresentStreetTwo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetTwo)
	if @rPresentStreetThree <> ''
	select @rPresentStreetThree = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetThree)
	if @rPresentCity <> ''
	select @rPresentCity = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCity)
	if @rPresentZipCode <> ''
	select @rPresentZipCode = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentZipCode)
	if @rPresentState <> ''
	select @rPresentState = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentState)
	if @rPresentCountry <> ''
	select @rPresentCountry = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCountry)
	if @rPresentContactNo <> ''
	select @rPresentContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentContactNo)
	if @rFamilyCast <> ''
	select @rFamilyCast = [sSetup].[fPortalXMLTagsReplaceReverse](@rFamilyCast)
	if @rAccountNumber <> ''
	select @rAccountNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAccountNumber)
	if @rBankName <> ''
	select @rBankName = [sSetup].[fPortalXMLTagsReplaceReverse](@rBankName)
	if @rBranch <> ''
	select @rBranch = [sSetup].[fPortalXMLTagsReplaceReverse](@rBranch)
	if @rEPFNumber<> ''
	select @rEPFNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rEPFNumber)
	if @rPanNumber <> ''
	select @rPanNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rPanNumber)
	if @rAdhaarNumber <> ''
	select @rAdhaarNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdhaarNumber)
	if @rWhatsAppContactNo <> ''
	select @rWhatsAppContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rWhatsAppContactNo)
	  
	 
	begin

		UPDATE sHrm.tEmployeeMaster 
		SET 
		ShortName = case when isnull(@rShortName,'') <> '' then @rShortName else ShortName end
		,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
		,IsObsolete   = case when isnull(IsObsolete,'') <> '' then IsObsolete else IsObsolete end
		,UpdatedUserId = @rCreatedUserId
		,UpdatedDateTime = sCommon.fGetDate()
		,Number = @rNumber
		WHERE Id = @EmpId and OrgId = @rOrgId AND ISNULL(IsOtherUser,0) = 0

		  
		UPDATE sHrm.tEmployeeJobDetail
		SET 
			EmployeeDesignationId = case when isnull(@designationid,0) <> 0 then @designationid else EmployeeDesignationId end,	 
			OrganizationDepartmentId = case when isnull(@departmenttid,0) <> 0 then @departmenttid else OrganizationDepartmentId end,
			DateOfJoining =	case when isnull(@rDateOfJoining,'') <> '' then @rDateOfJoining else DateOfJoining end,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			EmployeeTypeId = case when isnull(@emptypeid,0) <> 0 then @emptypeid else EmployeeTypeId end,
			EmployeeGroupId = case when isnull(@empgroupid,0) <> 0 then @empgroupid else EmployeeGroupid end,
			EmployeeGradeId = case when isnull(@employeegradeid,0) <> 0 then @employeegradeid else EmployeeGradeId  end ,
			DateOfleaving =  case when isnull(@rDateOfLeaving,'') <> '' then @rDateOfLeaving else DateOfleaving end,
			ReasonOfleaving = case when isnull(@rReason,'') <> '' then @rReason else ReasonOfleaving end,
			ProbationUptoDate = @rProbationUptoDate,
			AhdocUptoDate = @rAhdocUptoDate,
			PermanentDate = @rPermanentDate,
			DateOfResignation = @rDateOfResignation
			  
	  WHERE EmployeeId = @EmpId and OrgId = @rOrgId
	  
		Update sHrm.tEmployeePersonalDetail 
		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,
		Qualification =  case when isnull(@rQualification,'') <> '' then @rQualification else Qualification  end,
		BloodGroupId =  case when isnull(@bloodgroupid,0) <> 0 then @bloodgroupid else BloodGroupId  end,
		DateOfBirth =  case when isnull(@rDOB,0) <> 0 then @rDOB else DateOfBirth  end,
		IdentificationMark1 =  case when isnull(@rIdentificationMark1,'') <> '' then @rIdentificationMark1 else IdentificationMark1  end,
		UIDNumber =  case when isnull(@rUIDNumber,0) <> 0 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,
		CastCategoryId =case when isnull(@castcatagoryId,0) <> 0 then @castcatagoryId else FamilyCast  end
		where EmployeeId = @EmpId and OrgId = @rOrgId
		
  		UPDATE [sHrm].[tEmployeeCommunications]
		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 
		  ,[EmergencyContactNo] = case when isnull(@rMobileNo,'') <> '' then @rMobileNo else [EmergencyContactNo] end 
		  ,[PhoneNoCompany] = case when isnull(@rCompayPhoneNo,'') <> '' then @rCompayPhoneNo else [PhoneNoCompany] end 
		  ,[ExtensionNo] = case when isnull(@rExtensionNo,'') <> '' then @rExtensionNo else [ExtensionNo] end  
		  ,[CompanyEmail] =  case when isnull(@rCompayMailId,'') <> '' then @rCompayMailId else [CompanyEmail]  end   
		  ,[PersonalEmail] =  case when isnull(@rPersonalEmailid,'') <> '' then @rPersonalEmailid else [PersonalEmail]  end   
		  ,[MobileNumber] =  case when isnull(@rMobileNo,'') <> '' then @rMobileNo else [MobileNumber]  end      
		  ,[UpdatedUserId] = @rCreatedUserId
		  ,[UpdatedDateTime] =  sCommon.fGetDate() 
		  ,[WhatsAppContactNo] =  case when isnull(@rWhatsAppContactNo,'') <> '' then @rWhatsAppContactNo else [WhatsAppContactNo]  end    
		  ,PresentZipCode = case when isnull(@rPresentZipCode,'') <> '' then @rPresentZipCode else PresentZipCode  end    
		  ,PresentContactNo = case when isnull(@rPresentContactNo,'') <> '' then @rPresentContactNo else PresentContactNo  end    
		WHERE EmployeeId = @EmpId

		Update [sHrm].[tEmployeeStatutoryAndOther]
		SET
		AccountNumber = case when isnull(@rAccountNumber,'') <> '' then @rAccountNumber else AccountNumber  end, 
		BankName = case when isnull(@rBankName,'') <> '' then @rBankName else BankName  end,
		Branch = case when isnull(@rBranch,'') <> '' then @rBranch else Branch  end , 
		EPFNumber = case when isnull(@rEPFNumber,'') <> '' then @rEPFNumber else EPFNumber  end,
		PanNumber = case when isnull(@rPanNumber,'') <> '' then @rPanNumber else PanNumber  end
		where EmployeeId = @EmpId 
	end	
end
GO
PRINT N'Altering Procedure [sSecurity].[pVerifyMobileNumberForEmployeeOTP]...';


GO
ALTER PROCEDURE sSecurity.pVerifyMobileNumberForEmployeeOTP

	@rOrgId int = 0,
	@rMobileNumber nvarchar(50), 
	@rEmployeeId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount int = 0
	DECLARE @lUserId bigint = 0,@lId Bigint = 0
	DECLARE @newpwd VARCHAR(100) 

	SELECT @lCount = COUNT(EC.EmployeeId), @lId = EC.EmployeeId
	FROM sHrm.tEmployeeCommunications EC 
	INNER JOIN sHrm.tEmployeeMaster EM ON EC.EmployeeId = EM.Id 
	INNER JOIN sSecurity.tUser U ON U.SourceId = EC.EmployeeId AND U.SourceTypeId=95
	WHERE EC.MobileNumber = @rMobileNumber AND EM.OrgId=@rOrgId  AND EC.EmployeeId = @rEmployeeId
	GROUP BY EC.EmployeeId
	
	
	IF(@lCount > 0)
	BEGIN
	
		EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
		UPDATE sSecurity.tUser 
		SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
		WHERE SourceId = @lId AND OrgId = @rOrgId AND SourceTypeId = 95
		
		SELECT 1 AS Result,'' AS [Message], TempPasswordCode AS OTP,Id AS UserId FROM sSecurity.tUser 
		WHERE SourceId = @lId AND OrgId = @rOrgId AND SourceTypeId = 95

	END

	ELSE
	BEGIN 
		SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP, 0 AS UserId
	END
END
GO
PRINT N'Altering Procedure [sSecurity].[pVerifyMobileNumberForOTP]...';


GO
ALTER PROCEDURE [sSecurity].[pVerifyMobileNumberForOTP]

	@rOrgId int = 0,
	@rBatchId int =0,
	@rMobileNumber nvarchar(50), 
	@rAcademicId bigint 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount int = 0
	DECLARE @lUserId bigint =0
	DECLARE @newpwd VARCHAR(100) 

	SELECT @lCount = COUNT(SC.StudentId) 
	FROM  sStudent.tStudentCommunication SC
	INNER JOIN sStudent.tAcademic A ON A.StudentId = SC.StudentId
	INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
	WHERE SC.ParentContactNo = @rMobileNumber  
	--AND A.BatchId = @rBatchId    -- No Need as per mantis 0027903
	AND A.OrgId=@rOrgId  AND A.Id = @rAcademicId
	GROUP BY SC.StudentId
	
		IF(@lCount > 0)
		BEGIN
		
			SELECT SC.StudentId  INTO #UserId FROM  sStudent.tStudentCommunication SC
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SC.StudentId
			INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
			WHERE SC.ParentContactNo = @rMobileNumber 
			--AND A.BatchId = @rBatchId		-- No Need as per mantis 0027903
			AND A.OrgId=@rOrgId AND A.Id = @rAcademicId
		
			--END
			--SELECT * FROM #UserId
			SELECT @lUserId = StudentId FROM #UserId
			EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
			UPDATE sSecurity.tUser 
			SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
			WHERE SourceId = @lUserId AND OrgId = @rOrgId AND SourceTypeId = 2003
		
			SELECT 1 AS Result,'' AS [Message], TempPasswordCode AS OTP,Id AS UserId FROM sSecurity.tUser 
			WHERE SourceId = @lUserId AND OrgId = @rOrgId	

			DROP Table #UserId
		END

		ELSE
		BEGIN 
			SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP, 0 AS UserId
		END
		
	
END
GO
PRINT N'Altering Procedure [sStudent].[pDigitalFormChangeListGet]...';


GO

 
ALTER PROCEDURE [sStudent].[pDigitalFormChangeListGet]

	  @rId int=0,
	  @rOrgId smallint=0,
	  @rStudentCode nvarchar(100),
	  @rClassId bigint=0,
	  @rDivisionId bigint=0,
	  @rFormStatusId smallint = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	 
		SELECT 
			(SELECT MAX(AutoId) FROM sStudent.tDigitalFormStudent WHERE DigitalFormId = DF.Id AND AcademicId = DFS.AcademicId) as Id,
			DF.Id as DigitalFormId,
			DF.Code,
			DF.Title,
			SA.StudentId,
			SA.AcademicId,
			SA.Code as StudentCode,
			SA.Name,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.RollNo,
			SA.Number,
			ISNULL(DFSS.StatusId, 0) AS DigitalFormStatusId,
			ISNULL(SM.Title, '') AS DigitalFormStatus,
			ISNULL(DFSS.ActionDateTime, '') AS FormActionDateTime,
			(select count(1) from [sStudent].[tDigitalFormStudent] DFS1 
					Left join sCommon.tUpdateFieldMaster UFM On UFM.Id = DFS1.UpdateFieldId
				where DFS1.DigitalFormId = DF.Id and SA.AcademicId = DFS1.AcademicId and DFS1.StatusId=549	
				and ((isnull(SubFunctionalityName,'')<>'StudentImages' AND  isnull(DFS1.OldValue,'')<>isnull(DFS1.NewValue,'') ) OR (isnull(SubFunctionalityName,'')='StudentImages' AND isnull(DFS1.OldValueImage,cast('' as varbinary))<>isnull(DFS1.NewValueImage,cast('' as varbinary))))) PendingCount,
			(select count(1) from [sStudent].[tDigitalFormStudent] DFS1 
					Left join sCommon.tUpdateFieldMaster UFM On UFM.Id = DFS1.UpdateFieldId
				where DFS1.DigitalFormId = DF.Id and SA.AcademicId = DFS1.AcademicId and DFS1.StatusId=550
				and ((isnull(SubFunctionalityName,'')<>'StudentImages' AND  isnull(DFS1.OldValue,'')<>isnull(DFS1.NewValue,'') ) OR (isnull(SubFunctionalityName,'')='StudentImages' AND isnull(DFS1.OldValueImage,cast('' as varbinary))<>isnull(DFS1.NewValueImage,cast('' as varbinary))))
				) ApprovedCount,
			(select count(1) from [sStudent].[tDigitalFormStudent] DFS1 
					Left join sCommon.tUpdateFieldMaster UFM On UFM.Id = DFS1.UpdateFieldId
				where DFS1.DigitalFormId = DF.Id and SA.AcademicId = DFS1.AcademicId and DFS1.StatusId=551
				and ((isnull(SubFunctionalityName,'')<>'StudentImages' AND  isnull(DFS1.OldValue,'')<>isnull(DFS1.NewValue,'') ) OR (isnull(SubFunctionalityName,'')='StudentImages' AND isnull(DFS1.OldValueImage,cast('' as varbinary))<>isnull(DFS1.NewValueImage,cast('' as varbinary))))
			 ) RejectedCount,
			 (select count(1) from [sStudent].[tDigitalFormStudent] DFS1 
					Left join sCommon.tUpdateFieldMaster UFM On UFM.Id = DFS1.UpdateFieldId
				where DFS1.DigitalFormId = DF.Id and SA.AcademicId = DFS1.AcademicId --and DFS1.StatusId=551
				and ((isnull(SubFunctionalityName,'')<>'StudentImages' AND  isnull(DFS1.OldValue,'')=isnull(DFS1.NewValue,'') ) OR (isnull(SubFunctionalityName,'')='StudentImages' AND isnull(DFS1.OldValueImage,cast('' as varbinary))=isnull(DFS1.NewValueImage,cast('' as varbinary))))
			 ) NoChangeCount
		FROM 
			sStudent.tDigitalForm DF
			INNER JOIN (SELECT DigitalFormId,AcademicId FROM sStudent.tDigitalFormStudent GROUP By AcademicId,DigitalFormId) DFS ON DFS.DigitalFormId = DF.Id
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = DFS.AcademicId
			LEFT JOIN [sStudent].[tDigitalFormStudentStatus] DFSS ON DFSS.DigitalFormId = DF.Id AND DFSS.AcademicId = SA.AcademicId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = DFSS.StatusId
		WHERE 
			((DF.OrgId = @rOrgId)OR (@rOrgId=0))
			AND ((DF.Id = @rId) OR (@rId = 0))		
			AND ((SA.Code = @rStudentCode) OR (@rStudentCode=''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND (DFSS.StatusId = @rFormStatusId OR @rFormStatusId = 0)
	   ORDER BY Id Asc
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentBulkImagesAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentBulkImagesAdd]
	 
	@rNumber bigint,
	@rCode nvarchar(20),
	@rStudentPhoto varbinary(max),
	@rOrgId smallint,
	@rPhotoType nvarchar(50),
	@rOriginalStudentPhoto varbinary(max)
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DECLARE @lStudentId bigint
	
	SELECT @lStudentId=Id FROM sStudent.tStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId
	
	IF(ISNULL(@lStudentId,'') = '')
	BEGIN
		SELECT 1 AS Result
		RETURN
	END
	
	IF NOT EXISTS(SELECT StudentId FROM sStudent.tStudentImages WHERE StudentId=@lStudentId)
	BEGIN 
	INSERT INTO sStudent.tStudentImages
		(
			StudentId,
			StudentPhoto
		)
	VALUES
		(
			@lStudentId,
			NULL
		)		             
	END	 
	 
	 
	 IF @rPhotoType = 'TempStudentPhotos'
	 BEGIN
	  UPDATE sStudent.tStudentImages  SET StudentPhoto=@rStudentPhoto,OriginalStudentPhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId
	 END 
	 ELSE IF @rPhotoType = 'TempStudentFatherPhotos'
	 BEGIN
	  UPDATE sStudent.tStudentImages  SET FatherPhoto=@rStudentPhoto,OriginalFatherPhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId	 	 
	 END 
	 ELSE IF @rPhotoType = 'TempStudentMotherPhotos' 
	 BEGIN
	  UPDATE sStudent.tStudentImages  SET MotherPhoto=@rStudentPhoto,OriginalMotherPhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId
	 END
	 ELSE IF @rPhotoType = 'TempStudentRelativePhotos' 
	 BEGIN
	 UPDATE sStudent.tStudentImages  SET RelativePhoto=@rStudentPhoto,OriginalRelativePhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId	 
	 END
	 
	 SELECT 1 AS Result
	
	
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sTool].[pDeleteStaticData]...';


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

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


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

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

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

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


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

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

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

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

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

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

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

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

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

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

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

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

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

DELETE FROM sSystem.tStaticVersion

DELETE FROM sCommunication.tFeedBackAnswerGroupMaster

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

DELETE FROM sSystem.tTimeZone
DELETE FROM sTool.tTestCaseTypeMaster

DELETE FROM sAlumni.tEmployeementType

DELETE FROM sErp.tCampusTypeMaster

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

DELETE FROM sSecurity.tScreenHelp
DELETE FROM sSystem.tSettingInfo

DELETE FROM sProcurement.tOtherLocationSourceTypeMaster

DELETE FROM sCommon.tFieldTypeMaster
DELETE FROM sErp.tLeadInfrastructureMaster

DELETE FROM sHostel.tHostelEventMainTypeMaster

DELETE FROM sCertificate.tCertificateTypeMaster	
DELETE FROM sWorkflow.tActionStatusMaster
DELETE FROM sWorkflow.tApprovingDepartmentMaster
DELETE FROM sWorkflow.tWorkflowFunctionalityMaster

DELETE FROM sAcademic.tHomeworkCheckStatusMaster
DELETE FROM sAssessment.tExamTypeMaster

DELETE FROM sErp.tMarketingActivityMaster
DELETE FROM sErp.tMarketingSubActivityMaster
DELETE FROM sSetup.tCommonOrgGroupBatchMaster
DELETE FROM sWorkflow.tWorkflowFunctionalityMaster

DELETE FROM sAudit.tOperationMaster

DELETE FROM sAdmission.tInquiryMainStatusMaster
DELETE FROM sCertificate.tPrintTemplateFunctionalityMaster
DELETE FROM sErp.tTripLogStatusMaster

DELETE FROM sErp.tFollowupTypeMaster
DELETE FROM sErp.tSupportCategoryMaster
DELETE FROM sErp.tSupportPriorityMaster
DELETE FROM sErp.tSupportTicketStatusMaster


DELETE FROM sErp.tPlugInMaster
DELETE FROM sErp.tTagMaster

DELETE FROM sErp.tIssueTypeMaster

DELETE FROM sErp.tScreenFunctionalityMaster

DELETE FROM sHrm.tChangeTypeMaster


DELETE FROM sCommon.tDataMaster
DELETE FROM sCommon.tDataTypeMaster

DELETE FROM siTax.tStaticIncomeTaxSubSubGroup

DELETE FROM sCommunication.tStudentDocumentTypeMaster

DELETE FROM sCommon.tUploadFunctionalityMaster
DELETE FROM sCommunication.tEmployeeDocumentTypeMaster

DELETE FROM sErp.tCustomerMessageTypeMaster

DELETE FROM sActivity.tActivityMainTypeMaster
DELETE FROM sSecurity.tTraceabilityMaster
DELETE FROM sSecurity.tTraceabilityTrack

DELETE FROM sSecurity.tScreenScopeDetails
DELETE FROM sBiometric.tEmployeeConfigurationMaster
DELETE FROM sSetup.tEmployeeNameFormatMaster
DELETE FROM sStudent.tOnlineRegistrationDisplayFieldMaster

DELETE FROM sSetup.tFormTypeMaster
DELETE FROM sSetup.tFormButtonMaster

DELETE FROM sSecurity.tSysSuperScreen
DELETE FROM sAppraisal.tKPAStatus
--DELETE FROM sAttendance.tPeriodNoMaster

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


GO
ALTER PROCEDURE [sTool].[pUpgradeVersion]
	 
	@rVersionId int,
	@rVersion nvarchar(20),
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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


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

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



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

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

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

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

-- update tablerowid master data from excel to table

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

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

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



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




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId

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


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

IF NOT EXISTS(SELECT 1 FROM sCommon.tPublishDocumentMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN				
				INSERT INTO sCommon.tPublishDocumentMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 VALUES
						(sCommon.fGetIntIdForOrg(1,@rOrgGroupId),'Fee Receipt','Fee Receipt',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(2,@rOrgGroupId),'Bonafide','Bonafide',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(3,@rOrgGroupId),'Trial','Trial',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(4,@rOrgGroupId),'Charactor','Charactor',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(5,@rOrgGroupId),'Id Card','Id Card',0,1,Getdate(),1,Getdate(),@rOrgGroupId)
						
END


IF NOT EXISTS(SELECT 1 FROM sAdmission.tInquiryStatusMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sAdmission.tInquiryStatusMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,StatusId
					   --,HighlightColor
					   --,InquiryMainStatusId
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Title
						,Title
						,0
						,1
						,getdate()
						,NULL
						,NULL
						,@rOrgGroupId
						,Id	
						--,ISM.HighlightColor
						--,ISM.InquiryMainStatusId					
						FROM sCommon.tStatusMaster
						--INNER JOIN sAdmission.tInquiryStatusMaster ISM ON SM.Id = ISM.StatusId AND ISM.OrgGroupId = 1
						where statustypeId = 104


						UPDATE ISM  
							SET ISM.HighlightColor = ISM1.HighlightColor ,
								ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId
							FROM sAdmission.tInquiryStatusMaster ISM  
							INNER JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM.StatusId = ISM1.StatusId AND ISM1.OrgGroupId = 1
							INNER JOIN sCommon.tStatusMaster SM ON SM.Id = ISM1.StatusId 
							where SM.statustypeId = 104 AND ISM.OrgGroupId = @rOrgGroupId

						
	DECLARE @lMaxId int
	SET @lMaxId = sCommon.fGetIntIdForOrg(213,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sAdmission.tInquiryStatusMaster', @rCurrentNumber = @lMaxId
						
END

--static entry in tVisitorTypeMaster

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE Id = 1)
BEGIN	
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId])
     VALUES
           (1,
		   'Visitor',
		   'Visitor',
		   0,
		   1,
		   GetDate(),
		   NULL,
		   NULL,
		   1)
END

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE Id = 2)
BEGIN	
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId])
     VALUES
           (2,
		   'Parents',
		   'Parents',
		   0,
		   1,
		   GetDate(),
		   NULL,
		   NULL,
		   1)
END

--OrgGoup wise VisitorTypeMaster entry
IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE OrgGroupId = @rOrgGroupId AND Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId])
		 VALUES
			   (
			   sCommon.fGetIntIdForOrg(1,@rOrgGroupId),
			   'Visitor',
			   'Visitor',
			   0,
			   --1,
			   [sCommon].[fGetBigIntIdForOrg](3,@rOrgGroupId),
			   GetDate(),
			   NULL,
			   NULL,
			   @rOrgGroupId)
END

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE OrgGroupId = @rOrgGroupId AND Id = sCommon.fGetIntIdForOrg(2,@rOrgGroupId))
BEGIN
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId])
		 VALUES
			   (
			   sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
			   'Parents',
			   'Parents',
			   0,
			   --1,
			   [sCommon].[fGetBigIntIdForOrg](3,@rOrgGroupId),
			   GetDate(),
			   NULL,
			   NULL,
			   @rOrgGroupId)
END

--PeriodNoMaster Entry

IF NOT EXISTS(SELECT 1 FROM [sAttendance].[tPeriodNoMaster])
BEGIN	

INSERT INTO [sAttendance].[tPeriodNoMaster]
           ([Id]
           ,[Title]
           ,[IsObsolete])
     VALUES
          (1, '1', 0),
		  (2, '2', 0),
		  (3, '3', 0),
		  (4, '4', 0),
		  (5, '5', 0),
		  (6, '6', 0),
		  (7, '7', 0),
		  (8, '8', 0),
		  (9, '9', 0),
		  (10,'10', 0),
		  (11,'11', 0),
		  (12,'12', 0)

END

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

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

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

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


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

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

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


			
			
END


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

END


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

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

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

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

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

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

IF NOT EXISTS (SELECT 1 FROM sSecurity.tOrganizationTask  T   WHERE TaskId = 20596  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tOrganizationTask 
	(OrgGroupId, TaskId, AvailablePermission)
	SELECT  @rOrgGroupId,20596,2
END

--default permission for Lesson Plan Complete Task for Admin only (for execute permission)
IF NOT EXISTS (SELECT 1 FROM sSecurity.tOrganizationTask  T   WHERE TaskId = 31244  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tOrganizationTask 
	(OrgGroupId, TaskId, AvailablePermission)
	SELECT  @rOrgGroupId,31244,64
END

IF NOT EXISTS (SELECT * FROM sSecurity.tPermission   WHERE RoleId =sCommon.fGetIntIdForOrg(2,@rOrgGroupId) AND TaskId = 20596  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tPermission(TaskId, RoleId, Permission, IsObsolete, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime,OrgGroupId)
	SELECT  20596,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId
	FROM sSecurity.tOrganizationTask WHERE OrgGroupId = @rOrgGroupId
END

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

-- for SysSuperAdmin update password
UPDATE sSecurity.tUser SET LoginPassword='FxYuAuSiWcl4MZWDctl++A==' WHERE Id = sCommon.fGetBigIntIdForOrg(1,@rOrgGroupId)
UPDATE sSecurity.tUser SET LoginPassword='FxYuAuSiWcl4MZWDctl++A==' WHERE Id = 1

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

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


GO

CREATE PROCEDURE [sEMeeting].[pMeetingTypeMasterAdd]
	@rTitle nvarchar(100),
	@rOrgGroupId smallint,
	@rIsObsolete bit = 0,
	@rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY

	BEGIN TRANSACTION	

	BEGIN

	INSERT INTO sEMeeting.tMeetingTypeMaster
	(
		Name,
		OrgGroupId,
		IsObsolete,
		CreatedUserId,
		CreatedDateTime
	)
	VALUES
	(
		@rTitle,
		@rOrgGroupId,
		@rIsObsolete,
		@rCreatedUserId,
		sCommon.fGetDate()
	)

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


GO

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingScopeAdd]
			@rOnlineMeetingId bigint,
			@rScopeSourceTypeId smallint,
			@rScopeSourceId bigint,
			@rIsObsolete bit = 0,
			@rCreatedUserId bigint
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY

	BEGIN TRANSACTION	

	BEGIN

	If Exists(select OnlineMeetingId from sEMeeting.tOnlineMeetingScope where OnlineMeetingId=@rOnlineMeetingId AND ScopeSourceTypeId=@rScopeSourceTypeId
	AND ScopeSourceId=@rScopeSourceId)
		BEGIN
			SELECT @rScopeSourceId AS Result
			RETURN
		END 
ELSE
			BEGIN
			INSERT INTO sEMeeting.tOnlineMeetingScope
			(
			OnlineMeetingId,
			ScopeSourceTypeId,
			ScopeSourceId,
			IsObsolete,
			CreatedUserId,
			UpdatedUserId,
			CreatedDateTime,
			UpdatedDateTime
			)
			VALUES
			(
			@rOnlineMeetingId,
			@rScopeSourceTypeId,
			@rScopeSourceId,
			@rIsObsolete,
			@rCreatedUserId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			sCommon.fGetDate()
			)
			SELECT 1 AS Result

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


GO

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingScopeGet]
	@rOnlineMeetingId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

			 SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			WHERE OMS.OnlineMeetingId=@rOnlineMeetingId 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
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			WHERE OMS.OnlineMeetingId=@rOnlineMeetingId 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
			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
			WHERE OMS.OnlineMeetingId=@rOnlineMeetingId 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
			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	
				WHERE OMS.OnlineMeetingId=@rOnlineMeetingId 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
			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
			WHERE OMS.OnlineMeetingId=@rOnlineMeetingId 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
			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	
			WHERE OMS.OnlineMeetingId=@rOnlineMeetingId 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
			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	
			WHERE OMS.OnlineMeetingId=@rOnlineMeetingId AND OMS.ScopeSourceTypeId=95

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


GO
 
CREATE PROCEDURE [sEMeeting].[pOnlineMeetingGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rFromDate date = '',
	 @rToDate date = '',
	 @rEmployeeId bigint = 0,
	 @rMeetingTypeId smallint = 0,
	 @rIsCompleted int = -1,
	 @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 Status,
		    ISNULL(OM.Title,'') as Title,
			OM.StartDate AS TeacherStartDate,
			OM.EndDate AS TeacherEndDate
	  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
	  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 = -1))
			AND OM.IsCompleted <> 721			
	 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
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			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
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			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
			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
			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
			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	
				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
			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
			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
			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	
			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
			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	
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=95
	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 Status,
			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(OMS.MeetingProviderId,0) As MeetingProviderId,



			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 
	  WHERE 
			(OM.Id = @rId) AND OM.IsCompleted <> 721
	  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
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			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
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			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
			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
			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
			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	
				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
			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
			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
			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	
			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
			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	
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=95
	END
END TRY
BEGIN CATCH 
		ROLLBACK TRANSACTION
		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 date,
		@rStartTime datetime,
		@rEndDate date,
		@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,
		@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,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rOrgGroupId,
			@rMeetingTypeId,
			@rHostEmployeeId,
			@rStartDate,
			@rStartTime,
			@rEndDate, 
			@rEndTime,
			@rTitle,
			@rDescription,
			@rIsDisplayMeetingId,
			@rMeetingId,
			@rMeetingPass,
			@rIsReference,
			@rIsResource,
			@rIsCompleted,
			@rIsMeetingStarted,
			@rMeetingAccountId,
			@rIsMeetingCreated,
			@rIsObsolete,
			@rCreatedUserId,
			GetUtcDate()
		)
		    
	INSERT INTO sEMeeting.tOnlineMeetingScope
			(
			OnlineMeetingId,
			ScopeSourceTypeId,
			ScopeSourceId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
			)
			SELECT 
			@lNextNumber,
			ScopeSourceTypeId,
			ScopeSourceId,
			@rIsObsolete,
			@rCreatedUserId,
			GetUtcDate()
			from @rOnlineMeetingScopeList

	INSERT INTO sEMeeting.tOnlineMeetingReference
	(
	OnlineMeetingId,
	ReferencePath
	)
	SELECT
	@lNextNumber,
	ReferencePath
	from @rOnlineMeetingReferenceList

	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sEMeeting.tOnlineMeeting
	    SET
			 
           Id = @lNextNumber,
		   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,
			UpdatedUserId,
			UpdatedDateTime
			)
			SELECT 
			@rId,
			ScopeSourceTypeId,
			ScopeSourceId,
			@rIsObsolete,
			@rCreatedUserId,
			GetUtcDate()
			from @rOnlineMeetingScopeList
		
		delete from sEMeeting.tOnlineMeetingReference where OnlineMeetingId = @rId

		INSERT INTO sEMeeting.tOnlineMeetingReference
			(
			OnlineMeetingId,
			ReferencePath
			)
			SELECT
			@rId,
			ReferencePath
			from @rOnlineMeetingReferenceList
		
	    SELECT 11 AS Result
	
	 END  	

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


GO

CREATE PROCEDURE [sEMeeting].[pMeetingTypeGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT
		MTM.AutoId AS Id,
		MTM.Name AS Title
		FROM sEMeeting.tMeetingTypeMaster MTM
		WHERE MTM.IsObsolete = 0
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pMeetingAccountGet]...';


GO

CREATE 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 OMA.IsObsolete = 0 AND OMA.OrgGroupId =  @rOrgGroupId
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingTeacherGet]...';


GO

CREATE 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 = 'true')
			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 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingTeacherStudentListGet]...';


GO

 
 
CREATE PROCEDURE [sEMeeting].[pOnlineMeetingTeacherStudentListGet]
	 
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rMeetingTypeId int = 0,
	 @rStartDate date = '',
	 @rEndDate date = '',
	 @rIsCompleted int=-1,
	 @rTitle nvarchar(100) ='',
	 @rOrgGroupBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	 DECLARE @lConfigValue nvarchar(50)=''

	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 375 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	 IF @lConfigValue = ''
		SET @lConfigValue = 'False'
	 Print @lConfigValue
	  DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint,
	 @lClassName nvarchar(100)


	 SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId,
		@lClassName=CM.Title,@lCLassId=CM.Id
     FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
	 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
	 WHERE A.Id = @rSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
	 
	 IF(@lConfigValue = 'True')
  BEGIN
	 If (@rSourceTypeId = 2001)
	 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 (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 = -1))
				AND OM.IsCompleted <> 721
				
				ORDER BY OM.IsCompleted,OM.StartDate,OM.StartTime,OM.EndDate
			END
		
	IF (@rSourceTypeId = 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 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.StartDate 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

			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 = @rSourceId)
				AND ((Convert(int,OM.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
				AND ((OM.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				AND OM.IsCompleted <> 721
				ORDER BY OM.IsCompleted,OM.StartDate,OM.StartTime,OM.EndDate
		END
				
		END	
	ELSE IF(@lConfigValue = 'False')
	BEGIN
		If (@rSourceTypeId = 2001)
	 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 (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.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 = -1))
				AND OM.IsCompleted <> 721
				
				ORDER BY OM.IsCompleted,OM.StartDate,OM.StartTime,OM.EndDate
			END
		
			IF (@rSourceTypeId = 95)
			BEGIN 
			SELECT 
				OM.Id,
				DM.Title AS MeetingType,
				--EM.EmployeeName 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,
				OM.StartDate AS TeacherStartDateTime,
			    OM.StartDate 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

				WHERE
					((OM.MeetingTypeId = @rMeetingTypeId) OR (@rMeetingTypeId = 0))
					AND ((OM.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
					AND ((OM.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
					AND (OM.HostEmployeeId = @rSourceId)
					AND ((Convert(int,OM.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
					AND ((OM.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
					AND OM.IsCompleted <> 721
					ORDER BY OM.IsCompleted,OM.StartDate,OM.StartTime,OM.EndDate
			END
	END
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseOrderApprovedGet]...';


GO








CREATE 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 
		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 AND PO.StatusId = 3

		select POD.Id,
			   POD.PurchaseOrderId,
			   POD.OrgGroupId,
			   POD.PurchaseRequestDetailId,
			   POD.StockItemId,
			   POD.TotalQty,
			   POD.Remark, 
			   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'Creating Procedure [sPurchase].[pPurchaseOrderApprovedSearchGet]...';


GO





CREATE PROCEDURE [sPurchase].[pPurchaseOrderApprovedSearchGet]

	@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.RefNumber as Number,
				PO.RequestedBy, 
				PO.LocationId, 
				PO.PODate
		FROM		
				sPurchase.tPurchaseOrder PO (nolock)
		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 and PO.StatusId = 3
	 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].[pPurchaseOrderGet]...';


GO








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


GO



CREATE 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
		FROM		
				sPurchase.tPurchaseOrder PO (nolock)
		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'Creating Procedure [sPurchase].[pPurchaseRequestApprovedGet]...';


GO







CREATE 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 
		from   [sPurchase].[tPurchaseRequest] PR (nolock) 
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = PR.StatusId
		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'Creating Procedure [sPurchase].[pPurchaseRequestApprovedSearchGet]...';


GO


CREATE PROCEDURE [sPurchase].[pPurchaseRequestApprovedSearchGet]

	@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
		FROM		
				sPurchase.tPurchaseRequest PR (nolock)
		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 and PR.StatusId = 3
	 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].[pPurchaseRequestGet]...';


GO


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


GO


CREATE 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
		FROM		
				sPurchase.tPurchaseRequest PR (nolock)
		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].[pPurchaseVendorMasterGet]...';


GO


CREATE PROCEDURE [sPurchase].[pPurchaseVendorMasterGet]
	@rOrgGroupId [int],
	@rId [int] = 0,
	@rTitle [nvarchar](300) = '',
	--@rIsWildCardSearch [bit] = 1,
	@rCode [nvarchar](20) = '',
	@rVendorCategoryId [int] = 0,
	@rLocationId int=0	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		 --IF @rIsWildCardSearch = 1
		 --BEGIN
			 SET @rCode = sCommon.fSearchStringGet(@rCode)
		 --END
		     SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		
	     SELECT 
		  
		    VM.Id,
			VM.Code,
			VM.Title,
			VM.IsObsolete,
			VM.CreatedUserId,
			VM.CreatedDateTime,
			VM.UpdatedUserId,
			VM.UpdatedDateTime,
			--VM.Area,
			--VM.City,
			VM.ContactPersonName,
			--VM.Country,
			ISNULL(VM.CreditDays, 0) CreditDays,
			ISNULL(CAST(VM.CreditLimit AS DECIMAL(18, 2)), '0') CreditLimit,
			--VM.CreditLimit,
			VM.Email,
			VM.FaxNumber,			
			VM.PhoneNumberMobile,
			VM.PhoneNumberOffice,			
			--VM.State,
			VM.StreetFour,
			VM.StreetOne,
			VM.StreetThree,
			VM.StreetTwo,			
			VM.VendorCategoryId,
			VM.ZipCode,
			VC.Title VendorCategory,
			VM.State STATETITLE,
			VM.City CITYTITLE,
			VM.Country COUNTRYTITLE,
			VM.Area Area,
			VM.LocationID		
					
	   FROM sProcurement.tVendorMaster  VM (nolock)
	   LEFT JOIN   sProcurement.tVendorCategoryMaster VC
	   ON  VM.VendorCategoryId = VC.Id  
	   --LEFT JOIN  sCommon.tStateMaster SM 
	   --ON VM.StateId = SM.Id 
	   --LEFT JOIN   sCommon.tCityMaster CM 
	   --ON VM.CityId = CM.Id 
	   --LEFT JOIN    sCommon.tAreaMaster AM 
	   --ON VM.AreaId = AM.Id 
	   --LEFT JOIN   sCommon.tCountryMaster CAM
	   --ON VM.CountryId = CAM.Id 		     
	   WHERE ((VM.Id = @rId) OR (@rId = 0))
	   AND	((VM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	   AND ((VM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((VM.VendorCategoryId = @rVendorCategoryId) OR (@rVendorCategoryId = 0))
	   AND  VM.OrgGroupId = @rOrgGroupId
	   AND ((VM.LocationId = @rLocationId) OR (@rLocationId = 0))
	   AND VM.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].[pQuotationRequestGet]...';


GO


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


GO


CREATE 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
		FROM		
				sPurchase.tQuotationRequest QR (nolock)
		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'Creating Procedure [sPurchase].[pGoodsReceivedNoteGet]...';


GO


CREATE 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.DepartmentBranchId,
				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
	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].[pGoodsReceivedNoteSearchGet]...';


GO


CREATE 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.DepartmentBranchId,
				--GRN.VendorId,
				GRN.GRNNumber as Number,
				GRN.RequestedBy, 
				GRN.LocationId, 
				GRN.PODueDate
		FROM		
				sPurchase.tGoodsReceivedNote GRN (nolock)
		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'Creating Procedure [sPurchase].[pQuotationRequestDelete]...';


GO



CREATE PROCEDURE [sPurchase].[pQuotationRequestDelete]
		@rId bigint,
		@rStatusId int
 
AS
SET NOCOUNT ON

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

			if exists(select Id From sPurchase.tQuotationRequestDetail where QuotationRequestId = @rId)
			Begin
				delete from sPurchase.tQuotationRequestDetail
				where QuotationRequestId = @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].[pPurchaseRequestDelete]...';


GO



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

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

			if exists(select Id From sPurchase.tPurchaseRequestDetail where PurchaseRequestId = @rId)
			Begin
				delete from sPurchase.tPurchaseRequestDetail
				where PurchaseRequestId = @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].[pPurchaseOrderDelete]...';


GO


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

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

			if exists(select Id From sPurchase.tPurchaseOrderDetail where PurchaseOrderId = @rId)
			Begin
				delete from sPurchase.tPurchaseOrderDetail
				where PurchaseOrderId = @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].[pGoodsReceivedNoteDelete]...';


GO



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

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

			if exists(select Id From sPurchase.tGoodsReceivedNoteDetail where GoodsReceivedNoteId = @rId)
			Begin
				delete from sPurchase.tGoodsReceivedNoteDetail
				where GoodsReceivedNoteId = @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].[InvoiceGenerateDelete]...';


GO



CREATE PROCEDURE [sPurchase].[InvoiceGenerateDelete]
		@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].[pInvoiceGenerateSearchGet]...';


GO


CREATE 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
		FROM		
				sPurchase.tInvoiceGenerate IG (nolock)
		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'Creating Procedure [sPurchase].[pInvoiceGenerateGet]...';


GO


CREATE 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,
				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, 
			   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
	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
 
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,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberIGD+Id,
					OrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberIGD=@lNextNumberIGD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tInvoiceGenerateDetail', @rCurrentNumber = @lNextNumberIGD
			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	 
			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,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberIGDD+Id,
					OrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberIGDD=@lNextNumberIGDD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tInvoiceGenerateDetail', @rCurrentNumber = @lNextNumberIGDD
			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'Creating Procedure [sPurchase].[pSalesReturnSearchGet]...';


GO


CREATE 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
		FROM		
				sPurchase.tSalesReturn SR (nolock)
		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'Creating Procedure [sPurchase].[pSalesReturnGet]...';


GO


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


GO



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

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

			if exists(select Id From sPurchase.tSalesReturnDetail where SalesReturnId = @rId)
			Begin
				delete from sPurchase.tSalesReturnDetail
				where SalesReturnId = @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].[pGoodsReceivedNoteSRGet]...';


GO


CREATE 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.DepartmentBranchId,
				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'Creating Procedure [sPurchase].[pGoodsReceivedNoteSearchSRGet]...';


GO


CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchSRGet]

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

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.GRNNumber as Number,
				GRN.RequestedBy, 
				GRN.LocationId, 
				GRN.PODueDate
		FROM		
				sPurchase.tGoodsReceivedNote GRN (nolock)
			    INNER JOIN   sPurchase.tQualityCheck QC on QC.GoodsReceivedNoteId = GRN.Id AND QC.Id = @rQualityCheckId
			    INNER JOIN   sPurchase.tQualityCheckDetail QCD on QCD.QualityCheckId = QC.Id
		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 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'Creating Procedure [sPurchase].[pPurchaseStatusGet]...';


GO






CREATE PROCEDURE [sPurchase].[pPurchaseStatusGet]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select Id,
			   Title
		from   [sWf].[tWfStatusMaster] (nolock) 
		where  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].[pQualityCheckDelete]...';


GO



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

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

			if exists(select Id From sPurchase.tQualityCheckDetail where QualityCheckId = @rId)
			Begin
				delete from sPurchase.tQualityCheckDetail
				where QualityCheckId = @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].[pQualityCheckSearchGet]...';


GO


CREATE 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
		FROM		
				sPurchase.tQualityCheck QC (nolock)
		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'Creating Procedure [sPurchase].[pQualityCheckGet]...';


GO


CREATE 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
	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
 
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
			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
			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'Creating Procedure [sWf].[pWfApprovalAdd]...';


GO


CREATE 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
	    SELECT 21 AS Result 
	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 [sWf].[pWfApprovalGet]...';


GO



 
CREATE  PROCEDURE [sWf].[pWfApprovalGet]
			 @rWfFunctionalityId smallint=0,
			 @rFromDate date=null,
			 @rToDate date=null,
			 @rStatusId smallint=0,
			 @rOrgId smallint=0,
			 @rCode nvarchar(20) ='',
			 @rUserId bigint ,
			 @rApprovalRequestId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Declare @lRoleId int
	Select @lRoleId = RoleId from [sSecurity].[tUserRole] Where UserId = @rUserId

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PR.Id AS ApprovalRequestId,
		CONVERT(DATE,PR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseRequest PR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 1 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2040
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PR.Id AS ApprovalRequestId,
		CONVERT(DATE,PR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseRequest PR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 1 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2040
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PR.Id AS ApprovalRequestId,
		CONVERT(DATE,PR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseRequest PR
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 1 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PR.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2040
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UNION
	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		QR.Id AS ApprovalRequestId,
		CONVERT(DATE,QR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tQuotationRequest QR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 2 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = QR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2041
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,QR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,QR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((QR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		QR.Id AS ApprovalRequestId,
		CONVERT(DATE,QR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tQuotationRequest QR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 2 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = QR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2041
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,QR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,QR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((QR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		QR.Id AS ApprovalRequestId,
		CONVERT(DATE,QR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tQuotationRequest QR
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 2 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = QR.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2041
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,QR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,QR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((QR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))
	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UNION
	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PO.Id AS ApprovalRequestId,
		CONVERT(DATE,PO.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseOrder PO
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 3 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PO.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2042
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PO.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PO.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PO.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PO.Id AS ApprovalRequestId,
		CONVERT(DATE,PO.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseOrder PO
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 3 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PO.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2042
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PO.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PO.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PO.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PO.Id AS ApprovalRequestId,
		CONVERT(DATE,PO.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseOrder PO
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 3 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PO.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2042
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PO.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PO.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PO.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UNION
	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		GRN.Id AS ApprovalRequestId,
		CONVERT(DATE,GRN.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tGoodsReceivedNote GRN
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 4 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = GRN.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2043
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,GRN.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,GRN.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((GRN.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		GRN.Id AS ApprovalRequestId,
		CONVERT(DATE,GRN.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tGoodsReceivedNote GRN
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 4 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = GRN.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2043
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,GRN.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,GRN.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((GRN.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		GRN.Id AS ApprovalRequestId,
		CONVERT(DATE,GRN.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tGoodsReceivedNote GRN
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 4 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = GRN.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2043
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,GRN.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,GRN.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((GRN.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UNION
	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		SR.Id AS ApprovalRequestId,
		CONVERT(DATE,SR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tSalesReturn SR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 5 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = SR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2044
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,SR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,SR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((SR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		SR.Id AS ApprovalRequestId,
		CONVERT(DATE,SR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tSalesReturn SR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 4 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = SR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2043
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,SR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,SR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((SR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		SR.Id AS ApprovalRequestId,
		CONVERT(DATE,SR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tSalesReturn SR
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 5 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = SR.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2044
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,SR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,SR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((SR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))
END
GO
PRINT N'Creating Procedure [sWf].[pWfSetupGet]...';


GO


CREATE PROCEDURE [sWf].[pWfSetupGet]
	  @rId 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.AutoId = @rId AND WFS.OrgGroupId = @rOrgGroupId AND WFS.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 [sWf].[pWfSetupAdd]...';


GO



CREATE PROCEDURE [sWf].[pWfSetupAdd]
		@rId [smallint],
		@rWfTypeMasterId [smallint],
		@rLevel [smallint],
		@rOrgGroupId [smallint],
		@rWfFunctionalityId [smallint]
		--,
		--@rIsObsolete [bit]=false
       
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		BEGIN
			IF(@rId = 0)
			BEGIN
				INSERT INTO [sWf].[tWfSetup]
				(
				WfTypeMasterId,
				WfLevel,
				OrgGroupId,
				WfFunctionalityId,
				IsObsolete
				)
				VALUES
				(
				@rWfTypeMasterId,
				@rLevel,
				@rOrgGroupId,
				@rWfFunctionalityId,
				0
				)
				SELECT @rId = Scope_Identity()
			END
			ELSE
			BEGIN
				UPDATE [sWf].[tWfSetup]
				SET 
					WfTypeMasterId = @rWfTypeMasterId,
					WfLevel = @rLevel,
					OrgGroupId = @rOrgGroupId,
					WfFunctionalityId = @rWfFunctionalityId
				WHERE AutoId =@rId
				SELECT @rId
			END
		END
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Creating Procedure [sWf].[pWfUserGet]...';


GO


CREATE PROCEDURE [sWf].[pWfUserGet]
	  @rOrgGroupId smallint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select U.Id,
	           U.DisplayTitle 
		from   sSecurity.tUser U (nolock)
		INNER JOIN sSecurity.tUserRole UR ON UR.UserId = U.Id
		INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId 
		where U.IsObsolete='0' AND UR.IsObsolete='0' AND U.OrgId = @rOrgGroupId
		AND   R.Id <> ([sCommon].[fGetIntIdForOrg](21,@rOrgGroupId)) 
		AND   R.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'Creating Procedure [sWf].[pWfApprovingAuthorityAdd]...';


GO




CREATE 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
			)
			SELECT @rId = SCOPE_IDENTITY()
		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
			)
			SELECT @rId = SCOPE_IDENTITY()
		END
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Creating Procedure [sWf].[pWfApprovingAuthorityGet]...';


GO



CREATE PROCEDURE [sWf].[pWfApprovingAuthorityGet]
	  @rOrgId smallint,
	  @rWfFunctionalityId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select AutoId,
			   AuthoritySourceTypeId,
			   AuthoritySourceId,
			   OrgId,
			   WfFunctionalityId
        from   sWf.tWfApprovingAuthority (nolock)
        where  OrgId = @rOrgId AND WfFunctionalityId = @rWfFunctionalityId  
		ORDER BY WfFunctionalityId
	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 [sWf].[pWfRoleGet]...';


GO



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

BEGIN
	BEGIN TRY
		select Id,
			   Title 
	    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'Creating Procedure [sWf].[pWfFunctionalityMasterGet]...';


GO


CREATE PROCEDURE [sWf].[pWfFunctionalityMasterGet]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT Id,
			   Code,
			   Title,
			   IsObsolete
			   --Type
		FROM   sWf.tWfFunctionalityMaster(nolock)
		WHERE  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 [sWf].[pWfTypeMasterGet]...';


GO


CREATE PROCEDURE [sWf].[pWfTypeMasterGet]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT  Id,
				Code,
				Title,
				IsObsolete
		FROM    sWf.tWfTypeMaster(nolock)
		WHERE   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 [sAlert].[pAlertQueueDashboardGet]...';


GO
CREATE 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
		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
		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'Creating Procedure [sAssessment].[pRptLearningOutcomesGet]...';


GO
CREATE PROCEDURE [sAssessment].[pRptLearningOutcomesGet]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int, 
	 --@rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rDepartmentId int=0
	 		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	ESGM.Title AS ExamName,
	--TSD.EmployeeId,
	--EmpM.FirstName,
	--EmpM.MiddleName,
	--EmpM.LastName,
	--EmpM.FirstName + ' ' + EmpM.MiddleName + ' ' + EmpM.LastName AS EmployeeName,
	--EmpM.Code AS EmployeeCode,
	--SM.Id AS SubjectId,
	--SM.Code AS SubjectCode,
	--SM.Title AS SubjectName,
	DM.Id AS DivisionId,
	DM.DisplayTitle AS DivisionName,
	DM.OrderIndex AS DivisionOrder,
	CM.Id AS ClassId,
	CM.DisplayTitle AS ClassName,
	CM.OrderIndex AS ClassOrder,
	(CM.DisplayTitle + ' - ' + DM.DisplayTitle) AS ClassDivision,
	A.Id As AcademicId,
	EM.Id AS ExamId,
	--RD.Obtain AS SubjectObtain,
	--ED.Maximum AS SubjectMaximum,
	--CONVERT(Int,ROUND((ISNULL(RD.Obtain, 0) * 100) / ED.Maximum, 0)) AS SubjectPercentage,
	--RD.SubjectGrade,
	BM.Title AS BatchName,
	Round(R.Percentage,0)AS Percentage

	FROM 
		--sAssessment.tResultDetail RD
		sAssessment.tResult R 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.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 sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
		--INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
		--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			
		--LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.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 
			
	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 ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))		
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
END
GO
PRINT N'Creating Procedure [sAssessment].[pRptSubjectActivityMaxMarkGradeTwoColumnGet]...';


GO

CREATE PROCEDURE [sAssessment].[pRptSubjectActivityMaxMarkGradeTwoColumnGet]
	 
		@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 @GradeSetId int,@GradeString nvarchar(1000),@GradeStringRemark nvarchar(1000)
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

Declare @DecimalConfid nvarchar(20)=''
SELECT @DecimalConfid =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId

	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,
			[sStudent].[fStudentNameGet](StuM.FirstName , ISNULL(StuM.MiddleName,'') , StuM.LastName,OM.StudentNameFormatId ) AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			StuM.code,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			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 WHEN EM.IsDisplayTeacherSign = 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.MarksheetHeaderA4 
			ELSE 
			NULL END) AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
			--@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			TeacherSignCaption,
			EM.PrincipalSignCaption,
			ParentSignCaption,
			--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,
			SR.ResultRemark1,
			SR.ResultRemark2,	
			SR.ResultRemark3,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			
			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,
			ISNULL(SR.ImprovementArea,'') As ImprovementArea,
			ISNULL(SR.ProgressArea,'') AS ProgressArea,
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			ISNULL(SR.MyActivity,'') AS MyActivity,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			DivisionId,
			SM.ID,
			( EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			CONVERT(bit,@DecimalConfid) AS IsDecimal,
			AIS.Marks,
			SR.ExamSeatNo AS ExamSeatNo,					--add for 27710 mantis
			[sAssessment].[fSubjectWiseGradeGet](SA.Id,@rExamId,SAM.Id,SAM.ClassSubjectId,@rBatchId,@rClass) AS SubjectGrade,
			ED.Maximum AS SubjectMaximum

	 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.tEmployeeMaster EmpM 
				ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.IsObsolete = 0
			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 sStudent.tStudentCommunication SC ON SC.StudentId =StuM.ID
	    --LEFT JOIN @lAcademicId A ON A.AcademicId = SA.AcademicId AND A.ClassSubjectId = ED.ClassSubjectId
			----------------------------------------------------------------------------
			--sAssessment.tCCESubjectActivityMaster SAM 	
			--INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId 
			--INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			--INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			--INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CS.ClassId 
			--INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId			 
			--LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id 	
			--LEFT JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			--LEFT JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId	AND ED.ClassSubjectId = CS.ClassSubjectId 		 
			--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
			--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.AcademicId = 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.AcademicId AND EM.ID=RD.ExamId AND CS.ClassSubjectId=RD.ClassSubjectID 
		WHERE
			((SA.Id=@rAcademicId) OR(@rAcademicId=0))
			AND ((CS.ClassId=@rClass) OR (@rClass=0))
			And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
			And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
			and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			And AIS.ExamId=@rExamId
			AND ((STum.Code = @rCode) OR(@rCode=''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND StuM.StatusId = 1
			AND (ISNULL(STum.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
			AND SAM.IsObsolete = 0
		ORDER BY 
			SA.RollNo ASC,
			SAM.OrderIndex ASC,
			SSA.OrderIndex ASC;
END
GO
PRINT N'Creating Procedure [sAttendance].[pRptStudentRegisterSubjectWiseGet]...';


GO
 
CREATE 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
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rToDate = DATEADD (d,1,@rToDate)

	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

		
	From 
	sAttendance.tStudentRegister R	 
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=R.SubjectId
	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))
	END
END
GO
PRINT N'Creating Procedure [sBiometric].[pRptBiometricAttendanceAnalysisReportGet]...';


GO

CREATE PROCEDURE [sBiometric].[pRptBiometricAttendanceAnalysisReportGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int,
	@rBatchId int,
	@rEmployeeId bigint,
	@rEmployeeStatusId int,
	@rForYear int,
	@rForMonth int,
	@rDeptId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))


	SELECT	ISNULL(@rBuilder1,'') AS Builder1,
			@rBuilder2 AS Builder2,
			MT.EmployeeId AS EmployeeId,
			MT.EmpCode AS EmployeeCode,
			EM.FirstName + ' ' + EM.LastName AS EmployeeName,
			EWD.ForMonth AS Month,
			EWD.ForYear AS Year,
			DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDaysInMonth,
			EWD.WeekOffs AS WeekOffs,
			([sHrm].[fEmployeeHolidayGet](EM.Id,0, @rForYear,@rForMonth,@rBatchId,@rOrgId)) AS HoliDays,

			((CASE	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
						THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate)  + 1 
					WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
						THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 1
					ELSE @lMonthDay
			END) - ([sHrm].[fEmployeeHolidayGet](EM.Id,0, @rForYear,@rForMonth,@rBatchId,@rOrgId)))  AS WorkingDay,
			CAST(DATEDIFF(S,CAST(MT.Tot_OT as Time),CAST(MT.TotalHour as Time))/3600 AS VARCHAR(10)) + ':'
													 + CAST(DATEDIFF(S,CAST(MT.Tot_OT as Time),CAST(MT.TotalHour as Time))%3600/60 AS VARCHAR(10)) 
			 AS TotalHour,
			MT.Tot_Attn AS TotalAttendance,
			MT.Tot_Abs AS TotalAbsent,
			MT.Tot_WeekOFF AS TotalWeekOff,
			MT.Tot_Holiday AS TotalHoliday,
			MT.Tot_Leave AS TotalLeave,
			MT.Count_OT AS OTCount,
			MT.Tot_OT AS TotalOT,
			MT.Tot_Late AS TotalLate,
			Mt.Tot_Early AS TotalEarly,
			EM.ShiftId AS EmployeeShift

	FROM	sBiometric.tMonthTrans MT
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId
			INNER JOIN sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode = EM.ShiftId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId= EM.Id
			LEFT JOIN sHrm.tEmployeeWorkingDays EWD ON EWD.EmployeeId=EM.Id AND EWD.ForYear = YEAR(MT.Attn_dt) AND EWD.ForMonth = Month(MT.Attn_dt)
			
	WHERE	(EM.OrgId = @rOrgId OR @rOrgId = 0)
			AND (MT.SourceTypeId = 95 OR MT.SourceTypeId=0)
			AND MT.Attn_dt=cast(rtrim(@rForYear *10000+ @rForMonth *100+ 01) as datetime)

END


--[sActivity].[tWeekOffSetting]

--[sCommon].[tWeekOffRules]

--[sHrm].[fEmployeeHolidayGet]

--SELECT ROUTINE_NAME, ROUTINE_TYPE, SPECIFIC_NAME
--FROM INFORMATION_SCHEMA.ROUTINES
--WHERE ROUTINE_DEFINITION LIKE '%fEmployeeHolidayGet%'
GO
PRINT N'Creating Procedure [sBiometric].[pStudentTimeSheetListGe]...';


GO
create PROCEDURE [sBiometric].[pStudentTimeSheetListGe]
	@rOrgGroupId int,
	@rOrgId int,
	 @rFromDate DateTime,  
  @rToDate DateTime, 
	@rStudentId bigint,
	 @rClassId int,
	@rDivisionId int,
	@rOrgGroupBatchId int=0,
	@rTimeSheetStatus nvarchar(10) = '0',
	@rDepartmentId 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)
	
	)

	
	
	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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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' 
		 ELSE TM.PresentStatus END
		From #TempMonthTrans TM
		INNER JOIN sStudent.vStudentAcademic SA  ON SA.StudentId = TM.EmployeeId 


	Select 
		SA.AcademicId AS AcademicId,
		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 sBiometric.tMonthTrans MT  
	 INNER JOIN sStudent.vStudentAcademic SA  ON SA.StudentId = MT.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
	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.OrgGroupBatchId = @rOrgGroupBatchId)
			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 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))
	ORDER BY SA.RollNo

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


GO

CREATE PROCEDURE [sCommunication].[pCircularConsentAdd]
	 
        @rCircularId bigint,
		@rQuestionDescription nvarchar(max),
		@rAnsFieldTypeId int,
		@rAnsFieldList nvarchar(max)
	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	INSERT INTO [sCommunication].[tCircularConsent]
		(
			CircularId,
			QuestionDescription,
			AnsFieldTypeId,
			AnsFieldList
		)
	VALUES
		(
			@rCircularId,
			@rQuestionDescription,
			@rAnsFieldTypeId,
			@rAnsFieldList
		)

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


GO

CREATE PROCEDURE [sCommunication].[pCircularConsentGet]
	 
        @rCircularId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT
		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'Creating Procedure [sHrm].[pEmployeeReplacementDelete]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeReplacementDelete]
	 
        @rExistingEmployeeId BIGINT,
		@rTitle NVARCHAR(500)
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rTitle = 'Assign Teacher')
	BEGIN
		delete from sTimetable.tAssignTeacher where EmployeeId = @rExistingEmployeeId
	END

	IF (@rTitle = 'Teacher Subject Division')
	BEGIN
		
		delete from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId
		
		delete from sAcademic.tTeacherSubjectDivision where EmployeeId = @rExistingEmployeeId		
	END

	IF (@rTitle ='Time Table')
	BEGIN
		Delete sTimetable.tTimeTable where EmployeeId  = @rExistingEmployeeId
		
		DELETE sTimetable.tTeacherWorkLoad  WHERE EmployeeId = @rExistingEmployeeId 
	END
	
	IF (@rTitle ='User Access')
	BEGIN

		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		
		IF (@lExistingUserId IS NULL)
		BEGIN
			Return
		END
		ELSE
		BEGIN
		
			delete from sSecurity.tUserOrganization  WHERE UserId=@lExistingUserId

			delete from sSecurity.tUserAccess  WHERE UserId=@lExistingUserId
		END
	END

	IF (@rTitle ='Class Teacher')
	BEGIN
		Update sSetup.tDivisionMaster SET InchargeEmployeeId = 0 where  InchargeEmployeeId =  @rExistingEmployeeId
	END

	IF (@rTitle ='Lesson Plan')
	BEGIN
		Delete sAcademic.tLessonPlan where EmployeeId =  @rExistingEmployeeId
	END
END
GO
PRINT N'Creating Procedure [sLibrary].[pRptBookPurchaseListGet]...';


GO

CREATE PROCEDURE [sLibrary].[pRptBookPurchaseListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rAccessionNo nvarchar(50)='',
	 @rClassificationNo nvarchar(50)='',
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 @rBookSubjectDrop nvarchar(200)='',
	 @rBookSubjectText nvarchar(200)='',
	 @rFromPurchaseDate date='',
	 @rToPurchaseDate date=''
           
AS
SET NOCOUNT ON
BEGIN
	BEGIN	  
		SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
		SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
		SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
		SET @rAccessionNo = sCommon.fSearchStringGet(@rAccessionNo)
		SET @rClassificationNo = sCommon.fSearchStringGet(@rClassificationNo)
		SET @rBookSubjectText = sCommon.fSearchStringGet(@rBookSubjectText)
	END
	SELECT   
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Id AS BookId,
		BM.Code AS BookCode,
		BM.Title AS BookName,
		BM.Author,
		BM.Publisher,
		BM.ClassificationNo,
		BM.BookSubject,
		BM.AccessionNo,
		BM.Edition,
		BM.NoOfPages,
		BM.BookLanguage,
		BM.Supplier,
		BM.PurchaseDate,
		BM.Price,
		BM.ISBNNumber,
		BM.Location,
		BM.BookRemark,
		LM.ReportOrgTitle,
		LM.SmallAddress1,
		LM.SmallAddress2,
		BM.NoOfCopies,
		BM.BillNumber,
		BM.Currency,
		BM.BookEntryDate,
		SM.Title AS StatusName
	FROM  
		sLibrary.tBookMaster BM 
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
		INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId 
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.AccessionNo like @rAccessionNo) OR (@rAccessionNo=''))
		AND ((BM.ClassificationNo like @rClassificationNo) OR (@rClassificationNo=''))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.PurchaseDate >= @rFromPurchaseDate) OR (ISNULL(@rFromPurchaseDate,'') = ''))
		AND ((BM.PurchaseDate <= @rToPurchaseDate) OR (ISNULL(@rToPurchaseDate,'') =''))
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
 
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,
					OrgGroupId,
					@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
			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,
					OrgGroupId,
					@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
			
			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].[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
 
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
			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
			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
		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
 
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
		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
			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
		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
 
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
			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
			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
		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].[pGoodsReceivedNoteAdd]...';


GO



CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteAdd]
		@rId bigint,
		@rPurchaseRequestId bigint,
		@rPurchaseOrderId bigint,
		@rDepartmentBranchId int,
		@rVendorId int,
		@rPODueDate datetime,	
		@rRequestedBy nvarchar(100),
		@rOrgGroupId smallint,
		@rLocationId int,
		@rStatusId smallint,	
		@rBillToAddress nvarchar(1000),
		@rUserId bigint,
		@rDetailList sPurchase.GoodsReceivedNoteDetailType 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,
				DepartmentBranchId = @rDepartmentBranchId,
				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
			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,
				DepartmentBranchId,
				PODueDate,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				VendorId,
				BillToAddress,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rPurchaseRequestId,
				@rPurchaseOrderId,
				@rDepartmentBranchId,
				@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
			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
		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
EXECUTE sp_refreshsqlmodule N'[sStudent].[fDivisionInchargeDetailsGet]';


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



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pMonthlyAttenanceRegisterGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAssessment].[pRptStudentProfileGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pStudentAttendanceXMLInsert]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pIDNoGenerationGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pXMLStudentImportAdd]';


GO
EXECUTE sp_refreshsqlmodule N'[sAssessment].[pRptResultSheetStandardMultiExamGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttenanceRegisterGetNew1]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDelete]';



GO
EXECUTE sp_refreshsqlmodule N'[sAssessment].[pRptStudentAnalysisDetailsGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pUpdatePendingAsNAGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pMonthlyAttendaceImportAdd]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentLCVerificationGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptCountCategorywiseStudentGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pAPIAdmissionInquiryDetailGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pAPIAdmissionInquiryGet]';


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



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentHistoryAcademicWiseAdd]';


GO
EXECUTE sp_refreshsqlmodule N'[sAssessment].[pRptResultListConsolidateWithSubExamGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAssessment].[pRptResultSheetStandardMultiExamGet_Old]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentFullProfileGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentRegisterDetailsGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttenanceRegisterGetNew]';



GO
EXECUTE sp_refreshsqlmodule N'[sCanteen].[pRptCanteenIssueSlipGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pRptMonthlySummaryListDateWiseGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pRptStudentMonthlySummaryListGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentGenerateReport]';



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


GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pAdmissionFormGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pAdmissionInquiryGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAssessment].[pRptResultSheetStandardMultiExamWithAllTermGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pAdmissionGenerateReport]';


GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pRptAdmissionListWIthMeritMarksGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pRptAdmissionSummaryGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pRptPreviousStudentAnalysisGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pRptStudentNewAdmissionListGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pNewAdmissionGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pStudentAdmissionGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttenanceRegisterGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttenanceRegisterGet_HTML]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttendanceFollowupDetailGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttendanceFollowupListGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pRptDailyAttendanceList]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pRptMonthlyAttendanceStudentwise]';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pRptMonthlyStrengthAttendanceSummary]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pRptStudentAttendanceLateCountList]';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pStudentRegisterGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pStudentRegisterMobileAppGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pSubjectwiseAttendanceGet]';


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


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


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



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


GO
EXECUTE sp_refreshsqlmodule N'[sClient].[pIshaDetailStudentModelGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sEis].[pRptInquiryAdmissionGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pAdditionalFeeDashBoardGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pConsolidateFeeStatusDashboardGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pDepositSetupGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pExamptionFeeDashBoardGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pNotApplicableFeeDashBoardGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeePendingDetailListOtherGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeeProcessGenerateGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeeProcessSummaryGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeeStatusFeeHeadandBusRouteWiseGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeeStatusStudentAndFeeWiseGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeeStatusStudentWiseDetails]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeeStatusStudentWisewithDiscountGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeeSummaryGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptStudentCountStatusGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptStudentFeeDetailsGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptStudentLedgerGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptStudentWiseFeeDetailGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptSummaryFeeStatusGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptSummaryPendingFeeGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pStudentCountStatusDashBoardGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sHostel].[pRptHostelAttendanceSheetGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sMis].[pRptClassCapacityGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sMis].[pRptInquiryAdmissionGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sMis].[pRptStudentStrengthGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pEnrollmentStatusAdd]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[ppImportStudent_Update_Dynamicly]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptCastCategoryStudentStrengthGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptGenderwiseStudentStrengthGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptNewAdmissionStrengthSummaryGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptRelegionStudentStrengthGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentAttendanceSummaryGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentDetailListGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentListAsOnDateGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentListGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentRegisterWithAcademicDetailGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentStrengthDivisionStatusWiseGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentStrengthDivisionWiseGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentStrengthGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentTenureAndConductCertificateGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptTrancriptionCertificateGet]';




GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptVerifyStudentDataListGet]';




GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStrengthStatusLEFTWiseGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStrengthStatusWiseGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDataListGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDetailDelete]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDetailUpdate]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDetailUpdateGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentSummaryDashboard]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentVerificationUpdate]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pSUIDGenerationGet]';


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



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttendanceDataVerifyGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentIcardGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentViewProfileGet]';




GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pIDRegisterGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAcademic].[pOnlineLearningAssignmentStudentCountGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAcademic].[pOnlineLearningAssignmentViewListGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pOnlineLearningAbsentStudentListGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pOnlineLearningLectureAdd]';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAbsentStudentDashboardGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pStudentPresenceDashboardGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pStudentRecord]';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pChatGroupDetailGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pFeeFollowupGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pMorePendingfee]';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[PAttendanceNotAdd]';



GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[PFee]';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[PHomework]';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[PNoAbsentEmployee]';



GO
EXECUTE sp_refreshsqlmodule N'[sMis].[pRptStudentBirthdayList]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pDigitalFormStudentListGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pDigitalFormStudentStatusAdd]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pDigitalFormSubmittedStudentListGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[PNoOfAbsentStudent]';

GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptincopleteFieldGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentInformationFormGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentInformationFormTestGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentRegisterGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentRegisterWithAddressGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentRegisterWithSUIDAndDemographicDetailGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDashboardGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentProfileGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sTransport].[pRptBusAttendanceGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sTransport].[pRptStudentAttendanceRegister]';



GO
EXECUTE sp_refreshsqlmodule N'[sTransport].[pRptStudentAttendanceRegisterBlankGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentCustomSearchGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pGetStudentList]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentVerificationGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pAcademicDelete]';


GO
EXECUTE sp_refreshsqlmodule N'[sSetup].[pOrganizationWiseStudentDelete]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pImportStudent_New]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDetailFormGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pImportStudent]';

GO
EXECUTE sp_refreshsqlmodule N'[sSecurity].[pDashletGet]';


GO





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

