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

 
GO
PRINT N'Altering [sAdmission].[tAdmissionCustomSearch]...';


GO
ALTER TABLE [sAdmission].[tAdmissionCustomSearch] ALTER COLUMN [Id] INT NOT NULL;


GO
PRINT N'Creating PK_tAdmissionCustomSearch...';


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


GO
PRINT N'Altering [sAdmission].[tAdmissionInquiry]...';


GO
ALTER TABLE [sAdmission].[tAdmissionInquiry]
    ADD [InquiryReferenceRemark] NVARCHAR (200) NULL;


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


GO
ALTER TABLE [sAlert].[tAlertQueueDetail] ALTER COLUMN [Id] BIGINT NOT NULL;


GO
PRINT N'Creating PK_tAlertQueueDetail...';


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


GO
PRINT N'Altering [sAssessment].[tCCEFASubject]...';


GO
ALTER TABLE [sAssessment].[tCCEFASubject] ALTER COLUMN [Id] INT NOT NULL;


GO
PRINT N'Creating PK_tCCEFASubject...';


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


GO
PRINT N'Altering [sAssessment].[tTempAllExam]...';


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [FatherOccupation] NVARCHAR (50) NULL;


GO
PRINT N'Altering [sCommunication].[tAssignTask]...';


GO
ALTER TABLE [sCommunication].[tAssignTask]
    ADD [DueReasonRemark] NVARCHAR (500) NULL;


GO
PRINT N'Creating PK_tAssignTask...';


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


GO
PRINT N'Creating [sAudit].[tChargeDeleted]...';


GO
CREATE TABLE [sAudit].[tChargeDeleted] (
    [OrgId]                 SMALLINT        NOT NULL,
    [Id]                    BIGINT          NOT NULL,
    [Code]                  NVARCHAR (50)   NOT NULL,
    [SourceTypeId]          SMALLINT        NULL,
    [SourceId]              BIGINT          NULL,
    [GuestName]             NVARCHAR (200)  NULL,
    [Remark]                NVARCHAR (200)  NULL,
    [ReceiptNumber]         INT             NOT NULL,
    [ReceiptDate]           DATE            NOT NULL,
    [PayTypeId]             TINYINT         NOT NULL,
    [ChequeNo]              NVARCHAR (20)   NULL,
    [BankName]              NVARCHAR (200)  NULL,
    [IsObsolete]            BIT             NOT NULL,
    [BatchId]               INT             NOT NULL,
    [ChargeReceiptBookName] NVARCHAR (100)  NOT NULL,
    [OrgGroupBatchId]       INT             NOT NULL,
    [CreatedUser]           NVARCHAR (50)   NOT NULL,
    [CreatedDateTime]       DATETIME        NOT NULL,
    [UpdatedUser]           NVARCHAR (50)   NULL,
    [UpdatedDateTime]       DATETIME        NULL,
    [ReceiptAmount]         DECIMAL (12, 2) NULL,
    [ChequeDate]            DATE            NULL,
    [DeletededUser]         NVARCHAR (50)   NULL,
    [DeletedDateTime]       DATETIME        NULL
);


GO
PRINT N'Creating PK_tChargeDeleted...';


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


GO
PRINT N'Creating [sAudit].[tChargeDetailDelete]...';


GO
CREATE TABLE [sAudit].[tChargeDetailDelete] (
    [ChargeReceiptId] BIGINT          NOT NULL,
    [ChargeName]      NVARCHAR (150)  NOT NULL,
    [Amount]          DECIMAL (12, 2) NOT NULL
);


GO
PRINT N'Creating PK_Configuration...';


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


GO
PRINT N'Creating PK_tLessonPlanResource...';


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


GO
PRINT N'Creating PK_tAccountMaster...';


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


GO
PRINT N'Creating PK_tBudget...';


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


GO
PRINT N'Creating PK_tTransaction...';


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


GO
PRINT N'Creating PK_tTransactionApprove...';


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


GO
PRINT N'Creating PK_tTransactionApproveDetail...';


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


GO
PRINT N'Creating PK_tTransactionDetail...';


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


GO
PRINT N'Creating PK_tActivity...';


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


GO
PRINT N'Creating PK_tEventEnrollment...';


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


GO
PRINT N'Creating PK_tHealthCheckup...';


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


GO
PRINT N'Creating PK_tHealthCheckupAssign...';


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


GO
PRINT N'Creating PK_tHealthTrack...';


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


GO
PRINT N'Creating PK_tImmunizationChart...';


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


GO
PRINT N'Creating PK_tPlacement...';


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


GO
PRINT N'Creating PK_tPlacementInvite...';


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


GO
PRINT N'Creating PK_tAdmissionFormIssue...';


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


GO
PRINT N'Creating PK_tAdmissionInquiryFollowup...';


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


GO
PRINT N'Creating PK_tAlertConfiguration...';


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


GO
PRINT N'Creating PK_tAlertLog...';


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


GO
PRINT N'Creating PK_tAlertLogHistory...';


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


GO
PRINT N'Creating PK_tAlertQueue...';


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


GO
PRINT N'Creating PK_tAlertTrackHistory...';


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


GO
PRINT N'Creating PK_tSMSStatusMaster...';


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


GO
PRINT N'Creating PK_tConduct...';


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


GO
PRINT N'Creating PK_tKPAEmployee...';


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


GO
PRINT N'Creating PK_tKPAEmployeeDetail...';


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


GO
PRINT N'Creating PK_tKPAEmployeeRating...';


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


GO
PRINT N'Creating PK_tKPAStatus...';


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


GO
PRINT N'Creating PK_tAllBatchResult...';


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


GO
PRINT N'Creating PK_tAllBatchResultCoScholestic...';


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


GO
PRINT N'Creating PK_tAllBatchResultGrade...';


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


GO
PRINT N'Creating PK_tCCECSClass...';


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


GO
PRINT N'Creating PK_tCCEFAScore...';


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


GO
PRINT N'Creating PK_tGeneralExamCustomSearch...';


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


GO
PRINT N'Creating PK_tGradeSetDetail...';


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


GO
PRINT N'Creating PK_tLevelSetDetail...';


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


GO

 
GO
PRINT N'Altering [sCertificate].[vPrintTemplateBonafideCertificate]...';


GO



ALTER VIEW [sCertificate].[vPrintTemplateBonafideCertificate]
AS  
	SELECT 	
		B.Id,
		B.Number,
		B.AcademicId,
		SM.Code,
		[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,
		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,
		B.Remark AS ReceiptNo,
		SF.FatherName,
		SA.AdmissionDate,
		DP.Title AS DepartmentName,
		ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
		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,
		SM.RecordStatusId,
		SO.BirthState AS BirthState,
		CM1.Title AS AdmissionStandard,
		A.BatchId,
		GM.Title AS Gender,
        '[AdhaarNumber],[AdmissionDate],[AdmissionStandard],[AffiliationType],[Batch],[BirthPlace],[BirthState],[BonafideDate],[BonafiedReason],[Caste],[Category],[CertificateHeaderA4],[City],[CityState],[Class],[ClassName],[Code],[ColumnList],[DateOfBirth],[DegreeAwarded],[DepartmentName],[District],[Divisionname],[DivisionOrder],[DOBInWords],[FatherName],[FirstName],[Gender],[LastName],[LetterHeadMargin],[MiddleName],[MotherName],[Name],[Nationality],[Number],[OrgLogo],[OrgTitle],[PermanentCity],[PermanentContactNo],[PermanentCountry],[PermanentState],[PermanentStreetOne],[PermanentStreetThree],[PermanentStreetTwo],[PermanentZipCode],[PresentCity],[PresentContactNo],[PresentCountry],[PresentState],[PresentStreetOne],[PresentStreetThree],[PresentStreetTwo],[PresentZipCode],[PrincipalSignature],[ReceiptNo],[RecordStatusId],[RegistrationDetail],[ReligionName],[ReportOrgTitle],[RollNo],[SmallAddress1],[SmallAddress2],[StudentPhoto],[SubCaste],[Taluka]' As ColumnList
	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
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
GO

 
GO
PRINT N'Altering [sAdmission].[pAdmissionInquiryAdd]...';


GO

ALTER PROCEDURE [sAdmission].[pAdmissionInquiryAdd]
		 @rId bigint
		,@rFirstName nvarchar(100)
		,@rMiddleName nvarchar(100)
		,@rLastName nvarchar(100)
		,@rForClassId int
		,@rForBatchId	int =0
		--,@rForBatch	nvarchar(20)
		,@rDateOfBirth date
		,@rOrgId smallint
		--,@rStatusId	smallint
		,@rInquiryStatusMasterId int
		,@rStreetOne nvarchar(50)
		,@rStreetTwo nvarchar(50)
		,@rStreetThree nvarchar(50)
		,@rCountry nvarchar(50)
		,@rState nvarchar(50)
		,@rCity	nvarchar(50)
		,@rZipCode nvarchar(20)
		,@rContactNo nvarchar(20)
		,@rContactEmail	nvarchar(50)
		,@rRemark nvarchar(200)
		,@rInquiryModeId tinyint
		,@rInquiryReferenceId int
		,@rAdmissionCategoryId int
		,@rPreviousSchool nvarchar(200)
		,@rMeritMarks decimal(10,2) 
		,@rMeritGrade nvarchar(20)
		,@rMeritMarksBreakup nvarchar(100)
		,@rGenderId tinyint
		,@rFollowupDate date
		,@rFollowupRemark nvarchar(150)
		,@rCreatedUserId bigint
		,@rInquiryDate date
		,@rNumber bigint 
		,@rHandledBy nvarchar(100) 
		,@rOrgGroupId int,
		@rCastCategoryId int=0,
		@rIsHostelRequired bit=0,
		@rIsTransportRequired bit=0,
		@rIsValidateInquiryAsPerAdmission bit=0,
		@rIsGivenAdmissionForm bit=0,
		@rAlternateContactNo nvarchar(100)='',
		@rAlternateContactEmail	nvarchar(200) = '',
		@rMotherName nvarchar(100)='',
		@rDataEntryModeId smallint = 562 ,
		@rMinorityStatusId smallint = 0,
		@rLiveWithId smallint = 0,
		@rAdhaarNumber nvarchar(20)='',
		@rBloodGroupId smallint = 0,
		@rFatherName nvarchar(100)='',
		@rFatherOccupation nvarchar(50)='',
		@rFatherIncome int = 0,
		@rFatherContactNo nvarchar(50)='',
		@rFatherMail nvarchar(50)='',
		@rFatherQualification nvarchar(50)='',
	    @rMotherOccupation nvarchar(50)='',
		@rMotherIncome int=0,
		@rMotherContactNo nvarchar(50)='',
		@rMotherMail nvarchar(50)='',
		@rMotherQualification nvarchar(50)='',
		@rStream nvarchar(20)='',
		@rBoard nvarchar(50)='' ,
		@rInquiryReferenceRemark nvarchar(200) = ''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DECLARE @lOrgGroupBatchId int=0
	
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster BM WHERE BM.Id = @rForBatchId
	
	DECLARE @lConfigValue nvarchar(50)=''
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 341 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	 
	
	IF(@lConfigValue='OrgGroupBatch')
	BEGIN
		SELECT @rNumber = (ISNULL(MAX(Number),0) + 1) FROM sAdmission.tAdmissionInquiry AI
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId 
		WHERE BM.OrgGroupBatchId = @lOrgGroupBatchId
	END
	ELSE IF(@lConfigValue='Batch')
	BEGIN
		SELECT @rNumber = (ISNULL(MAX(Number),0) + 1) FROM sAdmission.tAdmissionInquiry AI
		WHERE AI.ForBatchId = @rForBatchId
	END
	ELSE IF (@lConfigValue = 'Continuous')
	BEGIN
		SELECT @rNumber =(ISNULL(MAX(Number),0) + 1) FROM sAdmission.tAdmissionInquiry  
		WHERE OrgGroupId = @rOrgGroupId
	END
	
	Declare @lStatusId smallint,@lIsValidateBirthdate bit,@lFromDateOfBirth date,@lToDateOfBirth date
	SET @lStatusId= 0
	
	if(@rIsValidateInquiryAsPerAdmission=1)
	Begin
		Select @lIsValidateBirthdate=IsValidateBirthdate,@lFromDateOfBirth=FromDateOfBirth,@lToDateOfBirth=ToDateOfBirth from  sAdmission.tAdmissionCriteria where ClassId=@rForClassId AND BatchID=@rForBatchId
		
		if(@lIsValidateBirthdate=1 AND @rDateOfBirth NOT between @lFromDateOfBirth And @lToDateOfBirth)
		BEGIN
			Select  -101 AS Result
			return
		End
	End
	 
 BEGIN TRANSACTION	
IF(@rId = 0)	
	BEGIN	

 DECLARE @lNextNumber BIGINT 
 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionInquiry', 0, 1, 1,@outNextNumber = @lNextNumber output
			
	INSERT INTO sAdmission.tAdmissionInquiry
		(
			 Id
			,FirstName
			,MiddleName
			,LastName
			,ForClassId			 
			,ForBatchId
			,DateOfBirth
			,OrgId
			,StatusId
			,StreetOne
			,StreetTwo
			,StreetThree
			,Country
			,State
			,City
			,ZipCode
			,ContactNo
			,ContactEmail
			,Remark
			,InquiryModeId
			,InquiryReferenceId
			,AdmissionCategoryId
			,PreviousSchool
			,MeritMarks
			,MeritGrade
			,MeritMarksBreakup
			,GenderId
			,FollowupDate
			,FollowupRemark
			,CreatedUserId
			,CreatedDateTime
			,InquiryDate
			,Number
			,HandledBy
			,OrgGroupId
			,InquiryStatusId,
			CastCategoryId,
			IsHostelRequired,
			IsTransportRequired,
			IsGivenAdmissionForm,
			AlternateContactNo,
			AlternateContactEmail,
			MotherName,
			DataEntryModeId
			,MinorityStatusId 
		    ,LiveWithId
			,AdhaarNumber
			,BloodGroupId
			,FatherName
			,FatherOccupation
			,FatherIncome
			,FatherContactNo
			,FatherMail
			,FatherQualification
			,MotherOccupation
			,MotherIncome
			,MotherContactNo
			,MotherMail
			,MotherQualification
			,Stream
			,Board
			,InquiryReferenceRemark
		)
	VALUES
		(
			 @lNextNumber
			,@rFirstName
			,@rMiddleName
			,@rLastName
			,@rForClassId
			,@rForBatchId			 
			,@rDateOfBirth
			,@rOrgId
			,@lStatusId
			,@rStreetOne
			,@rStreetTwo
			,@rStreetThree
			,@rCountry
			,@rState
			,@rCity
			,@rZipCode
			,@rContactNo
			,@rContactEmail
			,@rRemark
			,@rInquiryModeId
			,@rInquiryReferenceId
			,@rAdmissionCategoryId
			,@rPreviousSchool
			,@rMeritMarks
			,@rMeritGrade
			,@rMeritMarksBreakup
			,@rGenderId
			,@rFollowupDate
			,@rFollowupRemark
			,@rCreatedUserId
			,sCommon.fGetDate()
			,@rInquiryDate
			,@rNumber
			,@rHandledBy
			,@rOrgGroupId
			,@rInquiryStatusMasterId,
			@rCastCategoryId,
			@rIsHostelRequired,
			@rIsTransportRequired,
			@rIsGivenAdmissionForm,
			@rAlternateContactNo,
			@rAlternateContactEmail,
			@rMotherName,
			@rDataEntryModeId,
			@rMinorityStatusId,
			@rLiveWithId,
			@rAdhaarNumber,
			@rBloodGroupId,
			@rFatherName,
			@rFatherOccupation,
			@rFatherIncome,
			@rFatherContactNo,
			@rFatherMail,
			@rFatherQualification,
			@rMotherOccupation,
			@rMotherIncome,
			@rMotherContactNo,
			@rMotherMail,
			@rMotherQualification,
			@rStream,
			@rBoard,
			@rInquiryReferenceRemark
		)
		    SELECT @lNextNumber AS Result         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAdmission.tAdmissionInquiry
	    SET
			 FirstName=@rFirstName
			,MiddleName=@rMiddleName
			,LastName=@rLastName
			,ForClassId=@rForClassId
			,ForBatchId = @rForBatchId		 
			,DateOfBirth=@rDateOfBirth
			,OrgId=@rOrgId
			,StatusId=@lStatusId
			,StreetOne=@rStreetOne
			,StreetTwo=@rStreetTwo
			,StreetThree=@rStreetThree
			,Country=@rCountry
			,State=@rState
			,City=@rCity
			,ZipCode=@rZipCode
			,ContactNo=@rContactNo
			,ContactEmail=@rContactEmail
			,Remark=@rRemark
			,InquiryModeId=@rInquiryModeId
			,InquiryReferenceId=@rInquiryReferenceId 
			,AdmissionCategoryId=@rAdmissionCategoryId
			,PreviousSchool=@rPreviousSchool
			,MeritMarks=@rMeritMarks
			,MeritGrade=@rMeritGrade
			,MeritMarksBreakup=@rMeritMarksBreakup
			,GenderId=@rGenderId
			,FollowupDate=@rFollowupDate
			,FollowupRemark=@rFollowupRemark
			,UpdatedUserId=@rCreatedUserId
			,UpdatedDateTime=sCommon.fGetDate()
			,InquiryDate=@rInquiryDate
			,HandledBy=@rHandledBy
			,InquiryStatusId = @rInquiryStatusMasterId,
			CastCategoryId = @rCastCategoryId,
			IsHostelRequired=@rIsHostelRequired,
			IsTransportRequired=@rIsTransportRequired,
			IsGivenAdmissionForm =@rIsGivenAdmissionForm,
			AlternateContactNo = @rAlternateContactNo,
			AlternateContactEmail = @rAlternateContactEmail,
			MotherName = @rMotherName,
			DataEntryModeId = @rDataEntryModeId ,
			MinorityStatusId  = @rMinorityStatusId , 
			LiveWithId = @rLiveWithId ,
			AdhaarNumber = @rAdhaarNumber ,
			BloodGroupId = @rBloodGroupId ,
			FatherName = @rFatherName,
			FatherOccupation =  @rFatherOccupation ,
			FatherIncome = @rFatherIncome ,
			FatherContactNo = @rFatherContactNo ,
			FatherMail = @rFatherMail ,
			FatherQualification =@rFatherQualification ,
			MotherOccupation = @rMotherOccupation ,
			MotherIncome = @rMotherIncome ,
			MotherContactNo =  @rMotherContactNo ,
			MotherMail = @rMotherMail ,
			MotherQualification = @rMotherQualification ,
			Stream = @rStream ,
			Board  =  @rBoard ,
			InquiryReferenceRemark =@rInquiryReferenceRemark
		
		
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result      
	      
	 END  
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		SELECT ERROR_MESSAGE() AS ERROR
	END CATCH	
		
END
GO
PRINT N'Altering [sAdmission].[pAdmissionInquiryGet]...';


GO

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

BEGIN 
	
	IF(@rIsGivenAdmissionForm=1)
		SET @rIsGivenAdmissionForm = 1
  	IF(@rIsGivenAdmissionForm=2)
		SET @rIsGivenAdmissionForm =0
	 
	 
	 SET @rToDate = DATEADD(d,1,@rToDate)
	 --IF @rIsSearch = 1
		BEGIN
			SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName= sCommon.fSearchStringGet(@rLastName)
			SET @rHandledBy= sCommon.fSearchStringGet(@rHandledBy)
			--SET @rContactNo= sCommon.fSearchStringGet(@rContactNo)
		END
	
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CASE WHEN @rAdmissionInquiryIdText = 0 THEN AI.Number ELSE @rAdmissionInquiryIdText END AS AdmissionInquiryIdText,
			 AI.Id
			,AI.ForBatchId
			,AI.ForClassId
			,AI.StatusId
			,ISNULL(SM.Id,0) AS InquiryStatusMasterId
			,ISNULL(AI.GenderId,0) AS GenderId
			,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
			,ISNULL(IMM.Title,'') AS InquiryMode
			,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		    ,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		    ,AI.OrgId
		    ,ISNULL(AI.Number,0) AS InquiryNumber
		    ,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		    ,OM.DisplayTitle AS OrgName
		    ,BM.Title AS ForBatch
			,ISNULL(CM.Title,'') AS ClassName	
			,AI.FirstName
			,AI.MiddleName
			,AI.LastName
			,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
			,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
			,ISNULL(AI.DateOfBirth,'') As DateOfBirth
			,ISNULL(GM.Title,'') As Gender			
			,AI.ContactNo
			,AI.ContactEmail			
			,AI.StreetOne
			,AI.StreetTwo
			,AI.StreetThree
			,AI.Country
			,AI.State
			,AI.City
			,AI.ZipCode
			,ISNULL(AI.Remark,'') AS Remark						
		    ,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
			,ISNULL(AI.MeritMarks,0) AS MeritMarks
			,ISNULL(AI.MeritGrade,'') AS MeritGrade
			,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
			,SM.Title as StatusName	
			--,cast(replace(FollowupDate,'/','-') as date) As FollowupDate
			,ISNULL(AI.FollowupDate,'') As FollowupDate
			,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
			,ISNULL(IRM.Title ,'') AS InquiryReference	
			,ISNULL(SCM.Title,'') AS AdmissionCategory		
			,ISNULL(AI.HandledBy,'') AS HandledBy
			,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
			,ISNULL(AI.StudentId,0) AS StudentId,
			ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
			ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
			ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
			CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
			--ISNULL(AI.IsGivenAdmissionForm,0) AS IsGivenAdmissionForm,
			ISNULL(SM.HighlightColor,'') AS HighlightColor,
			ISNULL(SA.PreviousStandard,'') As PreviousStandard,
			AI.AlternateContactNo,
			AI.AlternateContactEmail
			,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
			ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
			ISNULL(AI.MotherName,'') AS MotherName,
			CASE WHEN AI.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode 
			,ISNULL(AI.MinorityStatusId,0) As MinorityStatusId
		    ,ISNULL(AI.LiveWithId,0) AS LiveWithId
			,ISNULL(AI.AdhaarNumber,'') AS AdhaarNumber 
			,ISNULL(AI.BloodGroupId,0) AS BloodGroupId
			 ,ISNULL(AI.FatherName,'') AS FatherName
			,ISNULL(AI.FatherOccupation,'') AS FatherOccupation 
			,ISNULL(AI.FatherIncome,0) AS FatherIncome 
			,ISNULL(AI.FatherContactNo,'') AS FatherContactNo
			,ISNULL(AI.FatherMail,'') AS FatherMail
			,ISNULL(AI.FatherQualification,'') AS FatherQualification
			,ISNULL(AI.MotherOccupation,'') As MotherOccupation
			,ISNULL(AI.MotherIncome,0) AS MotherIncome
			,ISNULL(AI.MotherContactNo,'') AS MotherContactNo 
			,ISNULL(AI.MotherMail,'') AS MotherMail 
			,ISNULL(AI.MotherQualification,'') AS  MotherQualification
			,ISNULL(AI.Stream,'') AS Stream
			,ISNULL(AI.Board,'') AS Board
			,ISNULL(CCM.Title,'') AS CasteCategory
			,ISNULL(AI.InquiryReferenceRemark,'') AS InquiryReferenceRemark

  FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
           --INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AI.StatusId AND StatusTypeId=104
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId  
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
			LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId 
			LEFT JOIN  scommon.tCastCategoryMaster CCM on CCM.Id = AI.CastCategoryId
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  --AND ((AI.StatusId=@rStatusId) OR (@rStatusId=0))
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (@rNumber=0))
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
	  
	  AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=0)OR (@rIsGivenAdmissionForm=-1))

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


GO
ALTER PROCEDURE [sAdmission].[pSortedAdmissionFormGET]

	 @rClassId  nvarchar(max) = '',
	 @rBatchId int = 0,
	 @rOrgId int,
	 @rFirstName nvarchar(100),
	 @rLastName nvarchar(100),
	 @rMinMeritMarks decimal(10,2),
	 @rMaxMeritMarks decimal(10,2),
	 @rFormNo int ,
	 @rCastCategoryId int=0,
	 @rDataEntryStatusId smallint=0
	 --@rTitle nvarchar(100),
	 --@rStatusId smallint
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
BEGIN 
	SELECT AF.Id,
		AFS.AdmissionFormId,
		AF.FormNo,
		AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
		AF.ContactNo,
		AF.ContactEmail,
		ISNULL(AF.MeritMarks,0) AS MeritMarks,
		AF.MeritGrade,
		CM.DisplayTitle AS ClassName,
		AFS.DiscussionDate AS DiscussionDate,
		CCM.Title AS CasteCategory,
		SM.Title AS DataEntryStatus
    FROM sAdmission.tAdmissionForm AF 
		Left JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId 
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=AF.CastCategoryId
		LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=AF.DataEntryStatusId
		
	WHERE  ((AF.FirstName like '%'+@rFirstName+'%') OR ISNULL(@rFirstName,'') = '')
		AND ((AF.LastName like'%'+ @rLastName+'%') OR ISNULL(@rLastName,'') = '')
		AND((AF.ForClassId IN(@rClassId)) OR (@rClassId=0))
		--AND(ISNULL(AF.ForClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId='')
		AND((AF.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((AF.OrgId=@rOrgId) OR (@rOrgId=0))
		AND((AF.MeritMarks >=@rMinMeritMarks) OR(@rMinMeritMarks =0.00))
		AND((AF.MeritMarks <=@rMaxMeritMarks) OR(@rMaxMeritMarks =0.00))
		AND((AF.FormNo=@rFormNo) OR (@rFormNo=0))
		AND((AF.CastCategoryId=@rCastCategoryId) OR (@rCastCategoryId=0))
		AND ((AF.DataEntryStatusId=@rDataEntryStatusId) OR (@rDataEntryStatusId = 0))
		ORDER BY AF.ForClassId
END
GO
PRINT N'Altering [sAlert].[pEmployeeProxySettingGet]...';


GO
ALTER PROCEDURE [sAlert].[pEmployeeProxySettingGet]
	
	     		
	 	 @rProxySettingId int,
         @rTemplate nvarchar(max),
         @rSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
		EM.MobileNumber AS MobileNo,	
		EM.CompanyEmail AS EmailId,
		replace (
		replace (
		replace (
		replace (
		replace(
		replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
		'[ProxyDate]',CONVERT(varchar,PS.ProxyDate,105)),
		'[PeriodNo]',PS.LectureNumber),
		'[Subject]',SM.Title),
		'[ClassDivision]',CM.Title +' - '+DM.Title),
		'[SendingUser]',EM1.EmployeeName)
		 AS MsgText,
		@rSubject AS Subject,
		95 AS ReceiverSourceTypeId,
		EM.EmployeeId AS ReceiverSourceId,
		EM.EmployeeName AS EmployeeName,
		PS.ProxyDate AS ProxyDate,
		PS.LectureNumber AS PeriodNo,
		SM.Title AS Subject,
		CM.Title +' - '+DM.Title AS ClassDivision,
		ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
		95 AS SourceTypeId,
		EM.EmployeeId AS SourceId,
		EM.OrgId,
		OM.OrgGroupId


	FROM 
		sHrm.vEmployeeCommonDetail EM
		INNER JOIN sTimetable.tProxySetting PS ON PS.EmployeeId = EM.EmployeeId 
		Inner Join [sTimetable].[tTimeTable] TT ON TT.Id=PS.TimeTableId
		left Join sHrm.vEmployeeCommonDetail EM1 On TT.EmployeeId = EM1.EmployeeId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = PS.DivisionId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
	WHERE
		PS.Id = @rProxySettingId 
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rFromObtain decimal(5,2)=0,
	 @rToObtain decimal(5,2)=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)='' 
	
	 --,@rcolumn_visible bit
	

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

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

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

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


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
		SI.StudentPhoto
		ELSE NULL END)AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		ISNULL(ESGM.Code,'') AS ExamCode,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		 
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		--(CASE EM.IsDisplayImageHeader WHEN 1 THEN
		--	OI.CertificateHeaderA4 
		--	ELSE NULL END)AS  MarksheetHeaderA4,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		@rIsDetail AS IsDetail,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark,
		RD.GraceMark,
		RD.KrupaMark,
		@GradeStringHtml,
		SR.ResultRemark3,
		EM.IsDisplayTotalMark,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		
		'' AS AchievementsTerm1,
		'' AS AchievementsTerm2,
		'' AS GeneralRemarkTerm1,
		'' AS GeneralRemarkTerm2,
		'' AS ResultRemark1Term1,
		'' AS ResultRemark2Term1, 
		'' AS ResultRemark1Term2,
		'' AS ResultRemark2Term2,
		SR.StudentHeight AS SR_HeightTerm1,
		SR.StudentWeight AS SR_WeightTerm1,
		SR.StudentHeight AS SR_HeightTerm2,
		SR.StudentWeight AS SR_WeightTerm2,
		ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm1,
	    ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm2,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm1,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm2,
	    HM.Title As HouseName,HM.Id as HouseId,
	    ISNULL(SO.AdhaarNumber,'') As AdhaarNumber,
	    ISNULL(SO.UIdNumber,'') As UIdNumber,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END)AS Gender,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		(SC.PresentStreetOne +' '+ SC.PresentStreetTwo +' '+ SC.PresentStreetThree +' '+ SC.PresentCity +' '+ SC.PermanentState) AS StudentAddress,
		ISNULL(Stum.SUId,'') AS SUId,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,
		ISNULL(StM.Title,'') AS StreamTitle,
		ISNULL(StuA.AdmissionFormNumber,0) AS AdmissionNo,
		ISNULL(StuA.AdmissionDate,'') AS AdmissionDate,
		Stum.MiddleName ,
		ISNULL(SF.FatherOccupation,'') AS FatherOccupation
				
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tStreamMaster StM ON CM.StreamId = Stm.Id
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId AND  ISNULL(EMP.IsOtherUser,0) = 0
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	Left JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=0))
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	Order By ED.DisplayOrder

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

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

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

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


GO


ALTER PROCEDURE [sAssessment].[pRptWeekStudentAnalysisListSubjectWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	                           
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rSubjectId int=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass nvarchar(max)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rDepartmentId int = 0,
	 @rFromMark decimal (5,2)=0,
	 @rToMark decimal (5,2)=0,
	 @rSubject nvarchar(max)='',
	 @rIsMultipleSubjects bit = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT r1.*
FROM
(	SELECT 	
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			ROW_NUMBER() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END  ORDER BY RD.Obtain ASC) rn,
			
			
			ESGM.Title AS Exam,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName  AS Name,
			
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			Sbj.Title AS SubjectName,
			Sbj.Id AS SubjectId,
			RD.Obtain ,
			R.TotalMarks,
			ED.Maximum,
			RD.SubjectGrade,
			@rIsMultipleSubjects AS IsMultipleSubjects
			  
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId		
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId =R.Id	
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId=A.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id 
			INNER JOIN sSetup.tSubjectMaster Sbj ON Sbj.Id  = CS.SubjectId
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		--AND Sbj.Id=@rSubjectId
		AND (Sbj.Id=@rSubjectId OR @rSubjectId=0) 
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
	    AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))
		AND ((Dept.Id = @rDepartmentId) OR (@rDepartmentId =0))
		AND ((RD.Obtain >= @rFromMark) OR (@rFromMark=0))
		AND ((RD.Obtain <= @rToMark) OR (@rToMark=0))
		AND (ISNULL(Sbj.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')

	)r1
	WHERE (r1.rn <= @rTop Or @rTop = 0)
END
GO
PRINT N'Altering [sAttendance].[pMonthlyRegisterStudentviewGet]...';


GO
 
ALTER PROCEDURE [sAttendance].[pMonthlyRegisterStudentviewGet]
	 	 
	 	 @rBatchId int,
	 	 @rAcademicId bigint,
	 	 @rAttendanceTypeId tinyint
	 	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
declare @lAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid1 nvarchar(max)=''
Declare @lAttendanceGridTotal nvarchar(max)=''
CREATE TABLE #AttedanceGridTable (AttendanceCount int,PresentCount int,AbsentCount int);

IF NOT EXISTS(select 1 From sAttendance.tMonthlyRegister where AcademicId=@rAcademicId and ForMonth=Month(GETDATE()) and ForYear=Year(GETDATE()))
BEGIN

--Current Month Details Add
		DECLARE @PresentCount DECIMAL(10,2)
		DECLARE @AbsentCount DECIMAL(10,2)
		DECLARE @AveragePresence DECIMAL(10,2)
		DECLARE @CurrentMonthDays DECIMAL(10,2)
		DECLARE @AttendanceCount INT 
		SET @CurrentMonthDays = (SELECT DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,getdate()),0))))
		DECLARE @YearNumber INT
		DECLARE @AbsentDays nvarchar(max)

		SET @YearNumber =Year(GETDATE())



		SET @PresentCount = (select count(AttendanceDate) AS PresentCount from sAttendance.tStudentRegister 
		where IsPresent=1 and AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()) AND (AttendanceTypeId=@rAttendanceTypeId))		

		SET @AbsentCount = (select count(AttendanceDate) AS AbsentCount from sAttendance.tStudentRegister 
		where IsPresent=0 and AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()) AND (AttendanceTypeId=@rAttendanceTypeId))		


		SET @AttendanceCount = (select count(AttendanceDate) AS PresentCount from sAttendance.tStudentRegister 
		where AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()) AND (AttendanceTypeId=@rAttendanceTypeId))		

		IF(@AttendanceCount = 0) BEGIN SET @AveragePresence = 0 END ELSE BEGIN
		SET @AveragePresence= (@PresentCount/@AttendanceCount)*100
		END

		SET @AbsentDays=(SELECT SUBSTRING(
		(SELECT ',' + CONVERT(varchar(10), Day(AttendanceDate))
		FROM  sAttendance.tStudentRegister s
		where AcademicId=@rAcademicId and IsPresent=0 and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate())	AND (AttendanceTypeId=@rAttendanceTypeId)		

		ORDER BY AcademicId
		FOR XML PATH('')),2,200000) AS CSV
)
END


SET 
	@lCuurentMonthAttedanceGrid = @lCuurentMonthAttedanceGrid + '<tr>
	<td align="left" scope="col">' + Isnull(LEFT(DATENAME(MONTH,Getdate()),10),'')  + '</td>
	<td align="left" scope="col">' +convert(varchar, isnull( @YearNumber,0))+ '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(@AttendanceCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(CAST(@PresentCount as INTEGER),0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(CAST(@AbsentCount as INTEGER),0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(@AveragePresence,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(@AbsentDays,0)) + '</td>
	</tr>'


	Select 
	@lAttedanceGrid = @lAttedanceGrid + '<tr>
	<td align="left" scope="col">' + Isnull(MY.MonthTitle,'')  + '</td>
	<td align="left" scope="col">' +convert(varchar,isnull( MY.YearNumber,0))+ '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AttendanceCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.PresentCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AbsentCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AveragePresence,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AbsentDays,0),103) + '</td>
	</tr>'

		From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND MR.AttendanceTypeId=@rAttendanceTypeId
		AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
	WHERE
		SN.AcademicId=@rAcademicId	
	ORDER BY MY.YearNumber,MY.MonthNumber;


INSERT INTO #AttedanceGridTable (AttendanceCount,
								 PresentCount,
								 AbsentCount)
				SELECT @AttendanceCount,@PresentCount,@AbsentCount;

INSERT INTO #AttedanceGridTable (AttendanceCount,
								 PresentCount,
								 AbsentCount)
				SELECT MR.AttendanceCount, MR.PresentCount, MR.AbsentCount

	From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND MR.AttendanceTypeId=@rAttendanceTypeId
		AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
	WHERE
		SN.AcademicId=@rAcademicId	
	ORDER BY MY.YearNumber,MY.MonthNumber;
 	
	select 
	@lAttendanceGridTotal = @lAttendanceGridTotal + '<tr>
	<td align="left" scope="col"></td>
	<td align="left" scope="col"></td>
	<td align="left" scope="col">' + convert(varchar, Sum(isnull( AGT.AttendanceCount,0))) + '</td>
	<td align="left" scope="col">' + convert(varchar, Sum(isnull(AGT.PresentCount,0))) + '</td>
	<td align="left" scope="col">' + convert(varchar, Sum(isnull(AGT.AbsentCount,0))) + '</td>
	<td align="left" scope="col"></td>
	<td align="left" scope="col"></td>
	</tr>'
		 From #AttedanceGridTable AGT;
	DROP TABLE #AttedanceGridTable;	 
	SELECT  isnull(@lAttedanceGrid ,'') + isnull(@lCuurentMonthAttedanceGrid ,'') + isnull(@lAttendanceGridTotal ,'') AS AttedanceGrid		
	--SELECT * FROM #AttedanceGridTable
		
END
GO
PRINT N'Altering [sAttendance].[pRptMonthlyAttendanceStudentwise]...';


GO

ALTER PROCEDURE [sAttendance].[pRptMonthlyAttendanceStudentwise]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rDepartmentId int,
	@rClassId int,
	@rDivisionId int,
	@rAttendanceTagId int,
	--@rFromDate date,
	@rUpToDate date,
	@rBatchId int,
	@rOrgId int	 ,
	@rAdmissionCategoryId int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lAttendanceDate nvarchar(MAX)
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		
		SA.AcademicId,
		ISNULL(SA.RollNo,0) as RollNo,
		SA.Name,
		SA.Code,
		CM.ID AS ClassId,
		CM.Title AS Class,
		CM.OrderIndex AS ClassOrderIndex,
		DM.Id AS DivisionId,
		DM.Title AS Division,
		DM.OrderIndex AS DivisionOrderIndex,

		DEM.Id As DepartmentId,
		DEM.Title AS DepartmentName ,
		DEM.OrderIndex As DepartmentOrderIndex ,

		SA.ClassName + '-'+ SA.DivisionName AS ClassDivision,
		ISNULL(AR.AttendanceTagCount,0) AS AttendanceTagCount,

		ISNULL((SELECT COUNT(SR.AcademicId)
						FROM sStudent.vStudentAcademic SA1 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA1.AcademicId And SR.AcademicId=SA.AcademicId
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId	 
							 AND SR.AttendanceDate <= @rUpToDate WHERE SR.IsPresent=1 AND ((SA.OrgId=@rOrgId)OR(@rOrgId=0))
							 AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS TotalPresentDays ,
		ISNULL((SELECT COUNT(SR.AcademicId)
						FROM sStudent.vStudentAcademic SA1 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA1.AcademicId And SR.AcademicId=SA.AcademicId
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId	 
							 AND SR.AttendanceDate <= @rUpToDate WHERE ((SA.OrgId=@rOrgId)OR(@rOrgId=0))
							 AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS TotalWorkingDays ,				
       -- ISNULL(MS.WorkingDays,0) As TotalWorkingDays ,

		STUFF(
         (SELECT DISTINCT  ', ' + CONVERT(NVARCHAR(MAX),SR.AttendanceDate,105)
           FROM
				sStudent.vStudentAcademic A INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.AcademicId  
			WHERE 
				 A.AcademicId = SA.AcademicId
				--AND (SR.AttendanceDate >= @rFromDate  AND SR.AttendanceDate <= @rToDate)
				AND (SR.AttendanceDate <= @rUpToDate)
				--AND SR.AttendanceTagId>0
				AND ((SR.AttendanceTagId =@rAttendanceTagId) OR (@rAttendanceTagId=0))
				AND ((SA.AdmissionCategoryId =@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			GROUP BY SR.AcademicId,AttendanceDate
          FOR XML PATH (''))
          , 1, 1, '')  AS UptoDate 
		 
	FROM 
		sStudent.vStudentAcademic SA 
		INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		INNER JOIN sSetup.tDepartmentMaster DEM on DEM.Id = CM.DepartmentId
		
		--Inner JOIN sAttendance.tMonthlySetup MS on MS.ClassId = SA.ClassId And MS.BatchId = SA.BatchId
		--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
		       
		LEFT JOIN
		(
			SELECT 
				SR.AcademicId,COUNT(SR.AttendanceTagId) AS AttendanceTagCount 
			FROM 
				sStudent.vStudentAcademic A
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.AcademicId 
				INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			WHERE 
				((A.ClassId=@rClassId) OR (@rClassId=0))
				AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND (A.OrgId = @rOrgId)
				AND (A.BatchId = @rBatchID)
				--AND (SR.AttendanceDate >= @rFromDate  AND SR.AttendanceDate <= @rToDate)
				AND (SR.AttendanceDate <= @rUpToDate)
				AND A.StatusId=1
				--AND SR.AttendanceTagId>0
				AND ((SR.AttendanceTagId =@rAttendanceTagId) OR (@rAttendanceTagId=0))
				AND ((A.AdmissionCategoryId =@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			GROUP BY SR.AcademicId
		) AR ON AR.AcademicId = SA.AcademicId
		
	WHERE 
		(SA.OrgId = @rOrgId)
		AND (SA.BatchId = @rBatchId)
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))

		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))

	AND ((SA.AdmissionCategoryId =@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
		--AND (AD.AdmissionDate <= @rFromDate)
		AND SA.StatusId=1
END
GO
PRINT N'Altering [sCanteen].[pAttendanceForBreakGet]...';


GO
ALTER PROCEDURE [sCanteen].[pAttendanceForBreakGet]
	 	 
	 	 @rBreakTypeId int,
		 @rBreakDate date,
		 @rClassId int = 0,
		 @rDivisionId int = 0
		 --@rOrgId int
		 --@rCanteenId int
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
	SELECT 
			RB.SourceId ,
			VA.Code,
			VA.Name,
			VA.SUId,
			ATR.BreakDate,
			RB.SourceTypeId,
			RB.BreaktypeId,
			BTM.Title AS BreakType,
			CASE WHEN ATR.SourceId IS NULL THEN 'false' ELSE 'true' END AS IsDeleted,
			VA.ClassId,
			VA.ClassName,
			VA.DivisionId,
			VA.DivisionName,
			VA.RollNo
				
  FROM 
             sStudent.vStudentLastAcademic  VA 
           INNER JOIN sCanteen.tRegisterForBreak RB ON VA.StudentId = RB.SourceId AND RB.SourceTypeId = 2003 
           LEFT JOIN sCanteen.tAttendanceForBreak ATR ON ATR.SourceId=VA.StudentId AND (ATR.BreakDate=@rBreakDate)
		   LEFT JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  RB.BreakTypeId 
			
            --INNER JOIN sHostel.tAssignRoom AR ON VA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
            --INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
   --         LEFT JOIN sCanteen.tAttendanceForBreak ATR ON ATR.SourceId=VA.StudentId 
			--LEFT JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  ATR.BreakTypeId 
			
			
		  
  WHERE 
  --((VA.OrgId = @rOrgId) OR (@rOrgId = 0))AND  
  RB.BreakTypeId = @rBreakTypeId AND
  (VA.ClassId = @rClassId OR ISNULL(@rClassId,0)=0) AND
  (VA.DivisionId = @rDivisionId OR ISNULL(@rDivisionId,0)=0)
	  
  ORDER BY VA.Code
  END
GO
PRINT N'Altering [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	
	
	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
	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
	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 [sCertificate].[pRptLeavingCertificateGet]...';


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

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

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


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


SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 178 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	
	
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--MR.PresentCount AS PresentDays ,
			--MR.TotalCount AS TotalDays ,
			L.Id,
			--(SELECT SUM(MR.PresentCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS PresentDaysSum ,
			--(SELECT SUM(MR.TotalCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS TotalDaysSum ,
			SM.Code,
			L.AcademicId,
			SM.FirstName,SM.MiddleName,SM.LastName,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			--0 As CastCategoryId,
			--ISNULL(SO.CastCategoryId,0) As CastCategoryId,
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			SA.PreviousSchool,
			SA.AdmissionDate,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			SO.GenderId,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(SC.PresentState,'') AS CityState,
			CM.DisplayTitle AS AdmissionStandard,
			CMS.DisplayTitle AS CurrentStandard,
			CMS.Title AS CurrentStandardTitle,
			--'' AS CurrentStandardInWords,
			SM.StatusId,
			L.LastExamName AS Result,
			L.LastExamResult AS FailOrPass,
			L.SubjectStudied AS SubjectNAme,
			L.RepeatDetail as PromotedorNot,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			--'' AS PromotedorNot,
			L.PromoteToClass  AS PromotedToClass,
			L.FeeDetail AS LastFeesPaid,
			L.FeeConcessionDetail AS AnyConcession,
			L.NCCScoutDetail  AS NCCScoutDetail,
			L.ExtraCurricularActivities AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			AD.PresentDaysAnnual AS PresentDaysSum,
			AD.TotalDaysAnnual AS TotalDaysSum,
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(L.ToCollege,'') AS ToCollege ,
			ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
			ISNULL(OM.University,'')AS University,
			@lSchoolRemark1 AS SchoolRemark1 ,
			@lSchoolRemark2 AS SchoolRemark2 ,
			@lSchoolRemark3 AS SchoolRemark3 ,
			@lSchoolRequiredSignature AS SchoolRequiredSignature,
			ISNULL(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
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			--INNER JOIN sStudent.tAcademic A ON L.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			INNER JOIN sSecurity.tUser U ON U.Id = L.CreatedUserId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			--LEFT JOIN  sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id 
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			--LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			--AND BM.OrgGroupBatchId=vSA.OrgGroupBatchId
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sSetup.tDivisionInchargeEmployee DIE ON vSA.DivisionId = DIE.DivisionId AND DIE.BatchId = vSA.BatchId
			AND DIE.Number = (SELECT MIN(Number) FROM sSetup.tDivisionInchargeEmployee WHERE  DIE.DivisionId = vSA.DivisionId AND DIE.BatchId = vSA.BatchId)
			LEFT JOIN sHrm.tEmployeeImages EI1 ON EI1.EmployeeId = DIE.EmployeeId
	WHERE 
				L.OrgId=@rOrgId
				AND	vSA.BatchId = @rBatchId 
				AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
				AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				--AND ((L.LCDate=@rLCDate) OR (ISNULL(@rLCDate,'')=''))
				--AND ((L.LeftDate=@rLeftDate) OR (ISNULL(@rLeftDate,'')=''))
				--AND ((L.LCCopy=@rLCCopy) OR (@rLCCopy=0))
				--AND ((L.LCBookNumber=@rLCBookNumber) OR (@rLCBookNumber=''))
				AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
				AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
				AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
				AND ((DM.ClassId=@rClassId) OR(@rClassId=0))
				--group by MR.PresentCount,MR.TotalCount, SubM.Title, SM.Code,L.AcademicId,SM.FirstName,SM.LastName,SM.MiddleName,SF.FatherName,SF.MotherName,NM.Title,
				--SO.CastCategoryId,RM.Title,so.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,SO.DateOfBirth,SO.BirthDateInWord,SA.PreviousSchool,
				--	SA.AdmissionDate,L.LeftDate,L.LCReason,L.LCProgress,L.LCConduct,L.LCRemark,L.LCDate,SO.GenderId,
				--	OM.CityName,OM.StateName,CM.DisplayTitle,CMS.DisplayTitle,SM.StatusId,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
END
GO
PRINT N'Altering [sCommon].[pOrganizationSetupRemove]...';


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

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


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

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

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

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

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

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

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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


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

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

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

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

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

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

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

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


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


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

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

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

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

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


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

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


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

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


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

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


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

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

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

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


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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 FROMsSetup.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




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

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


GO
ALTER PROCEDURE [sCommunication].[pAssignTaskAdd]
	 
	@rId bigint,
	@rAssignedDate date,
	@rDueDate date,
	@rAssignedToSourceTypeId smallint,
	@rAssignedToSourceId bigint,
	@rRemark nvarchar(300),
	@rIsCompleted bit,
	@rIsClosed bit,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rDueReasonRemark nvarchar(500)=''

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

	INSERT INTO sCommunication.tAssignTask
		(
			Id,
			AssignedDate,
			DueDate,
			AssignedToSourceTypeId,
			AssignedToSourceId,
			Remark,
			IsCompleted,
			IsClosed,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId,
			IsDeleted,
			DueReasonRemark
		)
	VALUES
		(
			@lNextNumber,
			@rAssignedDate,
			@rDueDate,
			@rAssignedToSourceTypeId,
			@rAssignedToSourceId,
			@rRemark,
			@rIsCompleted,
			@rIsClosed,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			0,
			@rDueReasonRemark
		)
		             
	END	 
	 ELSE
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tAssignTask
	    SET
			AssignedDate=@rAssignedDate,
			DueDate=@rDueDate,
			AssignedToSourceTypeId=@rAssignedToSourceTypeId,
			AssignedToSourceId=@rAssignedToSourceId,
			Remark=@rRemark,
			IsCompleted=@rIsCompleted,
			IsClosed=@rIsClosed,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			DueReasonRemark=@rDueReasonRemark
	      WHERE Id = @rId 	   
	 	 
		  SELECT @lNextNumber AS Result	   
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pAssignTaskByMeGet]...';


GO
ALTER PROCEDURE [sCommunication].[pAssignTaskByMeGet]
	 
	 @rOrgId int,
	 @rUserId bigint,
	 @rSyncedDateTime datetime
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		AT.Id,
		AT.AssignedDate,
		AT.DueDate,
		AT.Remark,
		AT.IsCompleted,
		AT.IsClosed,
		AT.IsDeleted,
		   AT.AssignedToSourceId AS AssignedToSourceId,
		AT.AssignedToSourceTypeId AS AssignedToSourceTypeId,
		(CASE 
		WHEN AT.AssignedToSourceTypeId=95 
		THEN (SELECT FirstName +' '+LastName FROM sHrm.tEmployeeMaster WHERE Id=AT.AssignedToSourceId AND  ISNULL(IsOtherUser,0) = 0 )
		WHEN AT.AssignedToSourceTypeId=2003
		THEN (SELECT FirstName +' '+LastName FROM sStudent.tStudentMaster WHERE Id=AT.AssignedToSourceId)
		END)AS AssignedToName,
		(CASE 
		WHEN AT.AssignedToSourceTypeId=95 
		THEN (SELECT Code FROM sHrm.tEmployeeMaster WHERE Id=AT.AssignedToSourceId AND ISNULL(IsOtherUser,0) = 0 )
		WHEN AT.AssignedToSourceTypeId=2003
		THEN (SELECT Code FROM sStudent.tStudentMaster WHERE Id=AT.AssignedToSourceId)
		END)AS AssignedToCode,
		AT.OrgId AS OrgId,
		AT.DueReasonRemark						
	FROM 
		sCommunication.tAssignTask AT
	WHERE 
		AT.CreatedUserId=@rUserId
		AND (AT.OrgId=@rOrgId OR @rOrgId=0)
		AND (AT.UpdatedDateTime > @rSyncedDateTime OR @rSyncedDateTime IS NULL)			
END
GO
PRINT N'Altering [sCommunication].[pAssignTaskGet]...';


GO
ALTER PROCEDURE [sCommunication].[pAssignTaskGet]
	 
	 @rId bigint,
	 @rOrgId int,
	 @rCreatedUserId bigint,
	 @rIsAssignTaskToMe bit,
	 @rStatus tinyint,
	 @rIsSearch bit,
	 @rSyncedAssignTaskId bigint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON	
BEGIN 
DECLARE @lSourceId bigint = 0
DECLARE @lSourceTypeId smallint = 0

SELECT @lSourceId = SourceId, @lSourceTypeId = SourceTypeId FROM sSecurity.tUser WHERE Id = @rCreatedUserId
IF(@rIsAssignTaskToMe = 1)
BEGIN
	SELECT 
			AT.Id,
			AT.AssignedToSourceTypeId,
			AT.AssignedToSourceId,
			CASE WHEN @rIsSearch = 1 THEN EM1.Code ELSE EM.Code END AS SourceCode,
			CASE WHEN @rIsSearch = 1 THEN ISNULL(EM1.FirstName, '') + ' ' + ISNULL(EM1.LastName, '') ELSE ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') END AS SourceName,
			CONVERT(varchar,AT.AssignedDate ,105) AS AssignedDate,
			CONVERT(varchar,AT.DueDate ,105) AS DueDate,
			AT.Remark,
			AT.IsCompleted,
			AT.IsClosed,
			AT.DueReasonRemark
	FROM 
			sCommunication.tAssignTask AT
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=95
			INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
			LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id=U.SourceId			
	WHERE 
			((AT.Id=@rId) OR (@rId=0))
		AND (AT.AssignedToSourceId=@lSourceId)
		AND (AT.AssignedToSourceTypeId = @lSourceTypeId)
		AND (AT.IsCompleted=(CASE 
			WHEN @rStatus=0 THEN 0
			WHEN @rStatus=1 THEN 1
			WHEN @rStatus=2 THEN 0
		END) OR @rStatus = 2)
		AND (AT.IsClosed=(CASE 
			WHEN @rStatus=2 THEN 1
			WHEN @rStatus=1 THEN 0
			WHEN @rStatus=0 THEN 0
		END) OR @rStatus = 1)
		AND AT.OrgId=@rOrgId
		AND ( AT.Id > @rSyncedAssignTaskId OR @rSyncedAssignTaskId = 0)
		AND AT.IsDeleted=0
			
	UNION ALL
	
	SELECT 
			AT.Id,
			AT.AssignedToSourceTypeId,
			AT.AssignedToSourceId,
			CASE WHEN @rIsSearch = 0 THEN SN.Code WHEN SN1.Id IS NOT NULL THEN SN1.Code ELSE EM1.Code END AS SourceCode,
			CASE WHEN @rIsSearch = 0 THEN SN.Name WHEN SN1.Id IS NOT NULL THEN SN1.FirstName + ' ' + SN1.LastName ELSE ISNULL(EM1.FirstName, '') + ' ' + ISNULL(EM1.LastName, '') END AS SourceName,
			CONVERT(varchar,AT.AssignedDate,105) AS AssignedDate,
			CONVERT(varchar,AT.DueDate,105) AS DueDate,
			AT.Remark,
			AT.IsCompleted,
			AT.IsClosed,
			AT.DueReasonRemark
	FROM 
			sCommunication.tAssignTask AT
			INNER JOIN sStudent.vStudentName SN ON SN.StudentId=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
			INNER JOIN sSetup.tBatchMaster BM ON SN.BatchId = BM.Id 
			AND BM.IsActive = 1
			INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
			LEFT JOIN sStudent.tStudentMaster SN1 ON SN1.Id=U.SourceId AND U.SourceTypeId=2003
			LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id=U.SourceId AND U.SourceTypeId=95
		
	WHERE 
			((AT.Id=@rId) OR (@rId=0))
		AND (AT.AssignedToSourceId=@lSourceId)
		AND (AT.AssignedToSourceTypeId = @lSourceTypeId)
		AND (AT.IsCompleted=(CASE 
			WHEN @rStatus=0 THEN 0
			WHEN @rStatus=1 THEN 1
			WHEN @rStatus=2 THEN 0
		END) OR @rStatus = 2)
		AND (AT.IsClosed=(CASE 
			WHEN @rStatus=2 THEN 1
			WHEN @rStatus=1 THEN 0
			WHEN @rStatus=0 THEN 0
		END) OR @rStatus = 1)
		AND AT.OrgId=@rOrgId
		AND ( AT.Id > @rSyncedAssignTaskId OR @rSyncedAssignTaskId = 0)
		AND AT.IsDeleted=0
END
ELSE
BEGIN
	SELECT 
			AT.Id,
			AT.AssignedToSourceTypeId,
			AT.AssignedToSourceId,
			EM1.Code AS SourceCode,
			ISNULL(EM1.FirstName, '') + ' ' + ISNULL(EM1.LastName, '') AS SourceName,
			CONVERT(varchar,AT.AssignedDate,105) AS AssignedDate,
			CONVERT(varchar,AT.DueDate,105) AS DueDate,
			AT.Remark,
			AT.IsCompleted,
			AT.IsClosed,
			AT.DueReasonRemark
	FROM 
			sCommunication.tAssignTask AT
			INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
			INNER JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=95
	WHERE 
			((AT.Id=@rId) OR (@rId=0))
		AND (AT.CreatedUserId=@rCreatedUserId OR @rCreatedUserId=0)
		AND (AT.IsCompleted=(CASE 
			WHEN @rStatus=0 THEN 0
			WHEN @rStatus=1 THEN 1
			WHEN @rStatus=2 THEN 0
		END) OR @rStatus = 2)
		AND (AT.IsClosed=(CASE 
			WHEN @rStatus=2 THEN 1
			WHEN @rStatus=1 THEN 0
			WHEN @rStatus=0 THEN 0
		END) OR @rStatus = 1)
		AND AT.OrgId=@rOrgId
		AND ( AT.Id > @rSyncedAssignTaskId OR @rSyncedAssignTaskId = 0)
		AND AT.IsDeleted=0
			
	UNION ALL
	
	SELECT 
			AT.Id,
			AT.AssignedToSourceTypeId,
			AT.AssignedToSourceId,
			SN1.Code AS SourceCode,
			SN1.FirstName + ' ' + SN1.LastName AS SourceName,
			CONVERT(varchar,AT.AssignedDate,105) AS AssignedDate,
			CONVERT(varchar,AT.DueDate,105) AS DueDate,
			AT.Remark,
			AT.IsCompleted,
			AT.IsClosed,
			AT.DueReasonRemark
	FROM 
			sCommunication.tAssignTask AT
			INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
			INNER JOIN sStudent.tStudentMaster SN1 ON SN1.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
		--INNER JOIN sStudent.vStudentName SN1 ON SN1.StudentId=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
	WHERE 
			((AT.Id=@rId) OR (@rId=0))
		AND (AT.CreatedUserId=@rCreatedUserId OR @rCreatedUserId=0)
		AND (AT.IsCompleted=(CASE 
			WHEN @rStatus=0 THEN 0
			WHEN @rStatus=1 THEN 1
			WHEN @rStatus=2 THEN 0
		END) OR @rStatus = 2)
		AND (AT.IsClosed=(CASE 
			WHEN @rStatus=2 THEN 1
			WHEN @rStatus=1 THEN 0
			WHEN @rStatus=0 THEN 0
		END) OR @rStatus = 1)
		AND AT.OrgId=@rOrgId
		AND ( AT.Id > @rSyncedAssignTaskId OR @rSyncedAssignTaskId = 0)
		AND AT.IsDeleted=0
END
END
GO
PRINT N'Altering [sCommunication].[pAssignTaskSearchGet]...';


GO
ALTER PROCEDURE [sCommunication].[pAssignTaskSearchGet]

	 @rId bigint,
	 @rOrgId int,
	 @rFromStartDate DateTime,
	 @rToStartDate DateTime,
	 @rFromDueDate DateTime,
	 @rToDueDate DateTime,
	 @rSourceTypeId int,
	 @rIsComplete bit,
	 @rIsClosed bit,
	 @rCreatedUserId bigint,
	 @rCode nvarchar(max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
IF(@rSourceTypeId = 95)
	BEGIN
	
		SELECT 
				DISTINCT AT.Id,
				AT.AssignedToSourceTypeId,
				AT.AssignedToSourceId,
				EM.Code AS SourceCode,
				EM.EmployeeName AS SourceName,
				CONVERT(varchar,AT.AssignedDate ,105) AS AssignedDate,
				CONVERT(varchar,AT.DueDate ,105) AS DueDate,
				AT.Remark,
				AT.IsCompleted,
				AT.IsClosed,
				OM.DisplayTitle AS Organization,
				ISNULL(CASE WHEN U.SourceTypeId = 2003 THEN (SELECT Name FROM sStudent.vStudentName WHERE StudentId = U.SourceId)
				ELSE (SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId) END,'') AS AssignedBy,
				ISNULL(AT.DueReasonRemark,'') AS DueReasonRemark
				--ISNULL((SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId),'') AS AssignedBy
		FROM 
				sCommunication.tAssignTask AT
				INNER JOIN sHrm.vExtEmployeeMaster EM ON EM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=95
				INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
				INNER JOIN sSetup.tOrganizationMaster OM ON AT.OrgId=OM.Id
		WHERE 
				((AT.Id=@rId) OR (ISNULL(@rId,0) = 0))
			AND ((AT.AssignedDate >= @rFromStartDate) OR (ISNULL(@rFromStartDate,0) = 0))
			AND ((AT.AssignedDate <= @rToStartDate) OR (ISNULL(@rToStartDate,0) = 0)) 
			AND ((AT.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,0) = 0))
			AND ((AT.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,0) = 0))
			AND ((AT.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId=0))
			AND ((AT.IsCompleted= @rIsComplete))
			AND (AT.IsClosed= @rIsClosed)
			AND (AT.OrgId=@rOrgId OR @rOrgId = 0)
			AND AT.IsDeleted=0
			AND ((EM.Code =@rCode) OR ISNULL(@rCode,'')='')
	END			
ELSE
	BEGIN
	print 'Yes'
		SELECT 
				DISTINCT AT.Id,
				AT.AssignedToSourceTypeId,
				AT.AssignedToSourceId,
				SN.Code AS SourceCode,
				SN.Name AS SourceName,
				CONVERT(varchar,AT.AssignedDate,105) AS AssignedDate,
				CONVERT(varchar,AT.DueDate,105) AS DueDate,
				AT.Remark,
				AT.IsCompleted,
				AT.IsClosed,
				OM.DisplayTitle AS Organization,
				ISNULL(CASE WHEN U.SourceTypeId = 2003 THEN (SELECT Name FROM sStudent.vStudentName WHERE StudentId = U.SourceId)
				 ELSE (SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId) END,'') AS AssignedBy
		FROM 
				sCommunication.tAssignTask AT
				INNER JOIN sStudent.vStudentName SN ON SN.StudentId=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
				INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
				INNER JOIN sSetup.tOrganizationMaster OM ON AT.OrgId=OM.Id
		WHERE 
				((AT.Id=@rId) OR (ISNULL(@rId,0) = 0))
				AND ((AT.AssignedDate >= @rFromStartDate) OR (ISNULL(@rFromStartDate,0) = 0))
				AND ((AT.AssignedDate <= @rToStartDate) OR (ISNULL(@rToStartDate,0) = 0)) 
				AND ((AT.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,0) = 0))
				AND ((AT.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,0) = 0))
				AND ((AT.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId=0))
				AND ((AT.IsCompleted= @rIsComplete))
				AND (AT.IsClosed= @rIsClosed)
				AND (AT.OrgId=@rOrgId OR @rOrgId = 0)
				AND AT.IsDeleted=0
				AND ((SN.Code =@rCode) OR ISNULL(@rCode,'')='') 
	END
END
GO
PRINT N'Altering [sCommunication].[pAssignTaskToMeGet]...';


GO
ALTER PROCEDURE [sCommunication].[pAssignTaskToMeGet]
	 
	 @rOrgId int,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId smallint,
	 @rSyncedDateTime datetime
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

IF(@rUserSourceTypeId=95)
BEGIN

	SELECT 
		AT.Id,
		AT.AssignedDate,
		AT.DueDate,
		AT.Remark,
		AT.IsCompleted,
		AT.IsClosed,
		AT.IsDeleted,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Id FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0 )
		WHEN U.SourceTypeId=2003
		THEN (SELECT Id FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedBySourceId,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN 95
		WHEN U.SourceTypeId=2003
		THEN 2003
		END)AS AssignedBySourceTypeId,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT FirstName +' '+LastName FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT FirstName +' '+LastName FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByName,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Code FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT Code FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByCode,
		AT.DueReasonRemark  
						
	FROM 
		sCommunication.tAssignTask AT
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=95
		INNER JOIN sSecurity.tUser U ON AT.CreatedUserId=U.Id
		
	WHERE 
		AT.AssignedToSourceId=@rUserSourceId
		AND (AT.OrgId=@rOrgId OR @rOrgId=0)
		AND (AT.UpdatedDateTime > @rSyncedDateTime OR @rSyncedDateTime IS NULL)
		AND ISNULL(EM.IsOtherUser,0) = 0 
	ORDER BY AT.DueDate
END
ELSE
BEGIN
	
	SELECT 
		AT.Id,
		AT.AssignedDate,
		AT.DueDate,
		AT.Remark,
		AT.IsCompleted,
		AT.IsClosed,
		AT.IsDeleted,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Id FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT Id FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedBySourceId,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN 95
		WHEN U.SourceTypeId=2003
		THEN 2003
		END)AS AssignedBySourceTypeId,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT FirstName +' '+LastName FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT FirstName +' '+LastName FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByName,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Code FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT Code FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByCode
					
	FROM 
		sCommunication.tAssignTask AT
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
		INNER JOIN sSecurity.tUser U ON AT.CreatedUserId=U.Id
		
	WHERE 
		AT.AssignedToSourceId=@rUserSourceId
		AND (AT.OrgId=@rOrgId OR @rOrgId=0)
		AND (AT.UpdatedDateTime > @rSyncedDateTime OR @rSyncedDateTime IS NULL)
	ORDER BY AT.DueDate
END

END
GO
PRINT N'Altering [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 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
  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)
  ) AS CG
  GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,OrderIndex,ReceiptBookId,ReceiptBook
  ORDER BY CG.StartDate,CG.OrderIndex

END
ELSE
BEGIN
SELECT SUM(CG.PayableAmount) AS PendingAmount 
,CollectionGroupId,StartDate,EndDate,CollectionGroupName,ReceiptBookId,ReceiptBook 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
  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)
  ) AS CG
  GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,OrderIndex,ReceiptBookId,ReceiptBook
  ORDER BY CG.StartDate,CG.OrderIndex
END
END
GO
PRINT N'Altering [sFee].[pFeeAllocationGet]...';


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

SELECT 
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.NotApplicableAmount,0.00) AS NotApplicableAmount,
			ISNULL(FA.Remark,'') AS Remark,
			ISNULL(FA.NotApplicableRemark,'') AS NotApplicableRemark,
			ISNULL(FA.AdditionalRemark,'') AS AdditionalRemark,
			ISNULL(FA.DiscountRemark,'') AS ExemptionRemark,
			FM.OrderIndex,
			0 AS ReceiptNumber,
			'1900-01-01'AS ReceiptDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			FS.CollectionGroupId,
			FM.FeeHeadId,
			FS.FeeDuration,
			ISNULL(FM.Code,'') AS FeeCode
			
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				ISNULL(FS1.FeeDuration,'')  AS FeeDuration
			FROM sFee.tFeeSetup FS1
			   
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = @rBatchId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,
				ISNULL(FS1.FeeDuration,'') AS FeeDuration
				 
			FROM sFee.tFeeSetup FS1
			 
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND(FO.SourceTypeId=@rSourceTypeId)
			WHERE
			 FS1.BatchId = @rBatchId
			AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
		) FS ON FS.FeeId=FM.Id
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
		    FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
			WHERE						
			 R.SourceId= @rSourceId
			AND ((R.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))
			AND R.IsObsolete = 0 
			AND R.BatchId = @rBatchId
			 GROUP BY FeeSetupId
		) R ON R.FeeSetupId = FS.Id	
WHERE 
	FS.BatchId=@rBatchId
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC
END
GO
PRINT N'Altering [sFee].[pFeeCollectionConsolidatedDashboardGet]...';


GO
 
 
 
ALTER PROCEDURE [sFee].[pFeeCollectionConsolidatedDashboardGet]

     @rOrgGroupId smallint=0,
     @rTypeId int=0,
     @rType nvarchar(20)='',
     @rCommonOrgGroupBatchId int=0,
	 @rFromDate date =null,
	 @rToDate date = null,
	 @rReceiptBookId int =0,
	 @rUserId bigint=0,
	 @rOrgId int =0,
	 @rCommonFeeId int =0
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
--If @rFromDate= NULL Set @rFromDate = ''
--  If @rToDate =NULL Set @rToDate = ''
 DECLARE @cols NVARCHAR(MAX),@query  NVARCHAR(MAX),@cols1 NVARCHAR(MAX), @cols2 NVARCHAR(MAX); 
	---Fee Collection Wise  
			IF(@rTypeId=1)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')					

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' 
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')	

					set @query = 'SELECT OrgGroupId,OrgGroupName,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  OMM.Id AS OrgGroupId ,OMM.Title AS OrgGroupName,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN  sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=R.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
					GROUP BY OMM.Title,OMM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY OrgGroupId,OrgGroupName  ORDER BY OrgGroupId'
					--print(@query)
					execute(@query)
				END
			ELSE IF( @rTypeId=11)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' 
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT ReceiptBookId,ReceiptBook,'+@cols2+' AS Total, ' + @cols1 + ' from 
					(
					SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
					GROUP BY RBM.Title,RBM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY ReceiptBookId,ReceiptBook ORDER BY ReceiptBookId'					
					--print(@query)
					execute(@query)
				 END
			ELSE IF( @rTypeId=12)
				BEGIN
						SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT UserId,UserName,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  U.Id As UserId,U.DisplayTitle AS UserName,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					GROUP BY U.id,U.DisplayTitle,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY UserId,UserName  ORDER BY UserId'
					print(@query)
					execute(@query)
				END
			ELSE IF (@rTypeId=13)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT OrgGroupId,OrgGroupName,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  OM.Id AS OrgGroupId ,OM.DisplayTitle AS OrgGroupName,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					GROUP BY OM.DisplayTitle,OM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY OrgGroupId,OrgGroupName ORDER BY OrgGroupId '
					print(@query)
					execute(@query)
				END
			ELSE IF (@rTypeId=14)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT FeeHeadId,FeeHead,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS total,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					GROUP BY FHM.Id,FHM.Title,PTM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY FeeHeadId,FeeHead ORDER BY FeeHeadId'
					
					execute(@query)
				END
			ELSE IF (@rTypeId=15)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT FeeHeadId,FeeMaster,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,SUM(RD.Amount) AS total,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
						INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
						INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
						INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
						INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
						INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
						INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
						WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
						AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
						AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
						GROUP BY FM.Id,FM.Title,PTM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY FeeHeadId,FeeMaster  ORDER BY FeeHeadId'
					execute(@query)
				END

			ELSE IF(@rTypeId =21)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((R.ReceiptBookId =@rReceiptBookId )OR(@rReceiptBookId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
				END
				ELSE
				BEGIN
				SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((R.ReceiptBookId =@rReceiptBookId )OR(@rReceiptBookId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
				END
				END
			ELSE IF(@rTypeId =22)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((U.Id =@rUserId )OR(@rUserId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((U.Id =@rUserId )OR(@rUserId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
				END
				END
			ELSE IF(@rTypeId =23)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((OM.Id =@rOrgId )OR(@rOrgId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((OM.Id =@rOrgId )OR(@rOrgId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
				END
				END
			ELSE IF(@rTypeId =24)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FHM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name 
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FHM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name
				END
				END
			ELSE IF(@rTypeId =25)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE  
					COGBM.Id=@rCommonOrgGroupBatchId
					AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name 
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE  
					COGBM.Id=@rCommonOrgGroupBatchId
					AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name
				END
				END
		
	
END
GO
PRINT N'Altering [sFee].[pFeeConsolidateDashBoardGet]...';


GO

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			
			SELECT * FROM sFee.tTempTotalPaidDetails  ttp
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON ttp.CollectionGroupId = CGM.Id
			WHERE ttp.CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((ttp.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			ORDER BY CGM.OrderIndex

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

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

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

			SELECT * FROM sFee.tTempPendingCount tpc
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON tpc.CollectionGroupId = CGM.Id
			WHERE tpc.CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((tpc.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			ORDER BY OrderIndex DESC
	 
			DROP TABLE #tempTotalPaidDetailsSync
			DROP TABLE #tempTotalStudentCountSync
			DROP TABLE #tempPendingCountSync

		END
	ELSE
		BEGIN
		IF  Exists(select 1 from sFee.tTempTotalPaidDetails where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
			BEGIN
	
				SELECT * FROM sFee.tTempTotalPaidDetails ttp 
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON ttp.CollectionGroupId=CGM.Id 
				WHERE ttp.CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((ttp.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) 
				ORDER BY CGM.OrderIndex

				SELECT * FROM sFee.tTempTotalStudentCount tts
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON tts.CollectionGroupId=CGM.Id 
				WHERE tts.CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((tts.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				ORDER BY CGM.OrderIndex

				SELECT * FROM sFee.tTempPendingCount tpc
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON tpc.CollectionGroupId=CGM.Id 
				WHERE tpc.CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((tpc.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				ORDER BY CGM.OrderIndex
				return
			END
		ELSE
			BEGIN

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

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

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

			SELECT * FROM sFee.tTempTotalPaidDetails  ttp
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON ttp.CollectionGroupId=CGM.Id 
			WHERE ttp.CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((ttp.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			ORDER BY CGM.OrderIndex	

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

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

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

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

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

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

END

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


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

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

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

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

IF(@rCollectionGroupId = 0)
	BEGIN

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

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

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

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

IF(@rCollectionGroupId = 0)
	BEGIN

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

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

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

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

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

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

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

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

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

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

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

)

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


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



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

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

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

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

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

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


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

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


GO

ALTER PROCEDURE [sFee].[pFeePaidAllBatchGet]    
      
     
  @rOrgId smallint,    
  @rCode nvarchar(20),
  @rIsObsolete bit = 0
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
      
	BEGIN  
	     
	 SELECT 
		  BM.Title As BatchName,
		  CM.Title +' - '+ DM.Title AS Class ,
		  RBM.Title AS ReceiptBook,
		  R.ReceiptNumber,    
		  R.ReceiptDate,  
		  PTM.Title AS PayType,
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  R.BankName,
		  STUFF((SELECT ', ' + CAST(FM.Title AS VARCHAR(100))  FROM sFee.tReceiptDetail RD INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		   WHERE RD.ReceiptId = R.Id  FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,2,' ') FeeDetail,
		  ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,    
		  ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
		  ISNULL(R.DiscountAmount,0)AS DiscountAmount,    
		  R.Remark 
	 FROM     
		   sFee.tReceipt R    
		  INNER JOIN sStudent.vStudentAcademic A    
		   ON A.AcademicId=R.SourceId 
   
		  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
		  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
		  INNER JOIN sCommon.tSourceTypeMaster STM    
		   ON STM.Id=R.SourceTypeId    
		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
		   ON PTM.Id=R.PayTypeId    
		  INNER JOIN sFee.tReceiptBookMaster RBM    
		   ON RBM.Id=R.ReceiptBookId    
		  INNER JOIN sSetup.tOrganizationMaster OM    
		   ON OM.Id=A.OrgId    

		  INNER JOIN sSetup.tBatchMaster BM    
		   ON BM.Id=R.BatchId     
        
	WHERE     
		 ((A.Code like @rCode) OR (ISNULL(@rCode,'')=''))    
		 AND (R.SourceTypeId=2001)    
		 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
		 AND (R.IsObsolete=@rIsObsolete) 

	ORDER BY R.ReceiptNumber DESC    
END
GO
PRINT N'Altering [sFee].[pFeeSummaryDashboard]...';


GO

 
ALTER PROCEDURE [sFee].[pFeeSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rBatchId int=0,
	@rDepartmentId int =0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 

	--DECLARE @lAdmissionCategoryId int =  0
	--SET @lAdmissionCategoryId = [sCommon].[fGetIntIdForOrg](1,@rOrgId)
	
	if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
		Create table #tTable(
			AcademicId bigint not null
		)
		Insert into #tTable
			select SA.AcademicId 
			FROM sFee.tFeeSetup FS
			INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId=FS.ClassId AND FS.BatchId = SA.BatchId AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
			where ((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			-- AND SA.AdmissionCategoryId=@lAdmissionCategoryId
			group by FS.ClassId,SA.AcademicId 

	IF(@rType = 'FeeList')
		BEGIN
			SELECT COUNT(SA.AcademicId)AS TotalCount,COUNT(T.PaidCount) AS PaidCount,(COUNT(SA.AcademicId)-COUNT(T.PaidCount))AS UnPaidCount
			, COUNT(PS.AcademicId) AS PartialCount
			FROM sStudent.vStudentAcademic SA 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			Inner Join #tTable FS  on  FS.AcademicId=SA.AcademicId
			LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,SA.AcademicId AS AcademicId FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId
			)T ON T.AcademicId = SA.AcademicId 

			LEFT JOIN 
			(
				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 0
					AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
					
				UNION 

				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 1
					AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
					
			) PS ON PS.AcademicId=SA.AcademicId

			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND SA.StatusId =1
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			--AND ACM.Code Like '%General%' 
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0	
		END
	ELSE IF(@rType = 'FeeGraph')
		BEGIN
		

			SELECT CM.Id,CM.Title,ISNULL(T.TotalCount,0)AS TotalCount,COUNT(T1.PaidCount) AS PaidCount,(ISNULL((T.TotalCount),0)-COUNT(T1.PaidCount))AS UnPaidCount,CM.OrderIndex
		FROM sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			LEFT JOIN sSetup.tClassMaster CM ON  CM.Id = SA.ClassId
			LEFT JOIN 
			(SELECT COUNT(SA1.AcademicId) AS TotalCount,SA1.ClassId AS ClassId FROM sStudent.vStudentAcademic SA1
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM1 ON SA1.AdmissionCategoryId = ACM1.Id
			Inner Join #tTable temp on SA1.AcademicId=temp.AcademicId
			WHERE ((SA1.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))AND SA1.StatusId =1
			--AND ACM1.Code Like '%General%' AND ACM1.IsObsolete = 0	
			--AND ACM1.ID = @lAdmissionCategoryId 
			AND ACM1.IsObsolete = 0
			GROUP BY ClassId
			)T ON T.ClassId = CM.Id	
			LEFT JOIN(
			SELECT COUNT(SA.AcademicId)as PaidCount,SA.AcademicId AS AcademicId,SA.ClassId AS ClassId FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			LEFT JOIN sSetup.tClassMaster CM ON  CM.Id = SA.ClassId
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))AND SA.StatusId =1
			--AND ACM.Code Like '%General%' AND ACM.IsObsolete = 0
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0		
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId,SA.ClassId
			)T1 ON T1.AcademicId = SA.AcademicId  AND CM.Id = SA.ClassId
			WHERE ((CM.OrgId =@rOrgId)OR(@rOrgId=0))
			AND SA.StatusId =1
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0
			--AND ACM.Code Like '%General%' AND ACM.IsObsolete = 0	
			GROUP BY CM.Title, CM.Id,T.TotalCount,CM.OrderIndex
			ORDER BY CM.OrderIndex

		
		END
	ELSE IF (@rType = 'FeeListDetails')
		BEGIN
		SELECT SA.RollNo,SA.Name,SA.Code, ISNULL(T.AcademicId,0) AS Pending, ISNULL(PS.AcademicId,0) AS [Partial],'' AS [Status]
			FROM sStudent.vStudentAcademic SA 
			Inner Join #tTable FS  on  FS.AcademicId=SA.AcademicId
			LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,SA.AcademicId AS AcademicId, SA.Code,SA.Name FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId, SA.Code,SA.Name
			)T ON T.AcademicId = SA.AcademicId
			LEFT JOIN 
			(
				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 0
					AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
					
				UNION 

				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 1
					AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
					
			) PS ON PS.AcademicId=SA.AcademicId


			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND SA.StatusId =1
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))	 			
		END

	ELSE IF(@rType='FeeCollection')
		BEGIN
			SELECT Isnull(Sum(R.ReceiptAmount),0.00) as TodayCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate=CAST(GETDATE() as DATE))

			SELECT ISNULL(Sum(R.ReceiptAmount),0.00) as MonthlyCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate>=CAST(DATEADD(DD,-(DAY(GETDATE() -1)), GETDATE()) as DATE) AND R.ReceiptDate<=CAST(DATEADD(DD,-(DAY(GETDATE())), DATEADD(MM, 1, GETDATE())) as DATE))

			SELECT Isnull(Sum(R.ReceiptAmount),0.00) as UptodateCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate<=CAST(GETDATE() as DATE))
		END
		Drop Table #tTable
END
GO
PRINT N'Altering [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)
				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)
				) 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)  
						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	
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex
			ORDER BY OrgId,FHM.OrderIndex
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 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,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				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)
				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)
				) 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)  
						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	
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.OrgId,O.Title,FS.FeeId,FS.FeeName,FS.OrderIndex
			ORDER BY OrgId,FS.FeeId
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 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,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				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)
				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)
				) 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)  
						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
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.OrgId,O.Title,CGM.Id,CGM.Title,CGM.OrderIndex
			ORDER BY OrgId,CGM.Id
	 END
	END
ELSE IF(@rFilterType = 'Departmentwise')
	BEGIN
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		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
		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)
				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)
				) 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)  
						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	
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.DepartmentId,SA.DepartmentName,FHM.Id,FHM.Title,FHM.OrderIndex
			ORDER BY DepartmentId,FHM.Id
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		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
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				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)
				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)
				) 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)  
						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	
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.DepartmentId,SA.DepartmentName,FS.FeeId,FS.FeeName,FS.OrderIndex
			ORDER BY DepartmentId,FS.FeeId
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		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
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				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)
				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)
				) 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)  
						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
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.DepartmentId,SA.DepartmentName,CGM.Id,CGM.Title,CGM.OrderIndex
			ORDER BY DepartmentId,CGM.Id
	 END
	END
ELSE IF(@rFilterType = 'ReceiptBookwise')
	BEGIN
	IF(@rFeeType = 'FeeHeadwise')
	BEGIN
	 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
		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,
					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)
				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)
				) 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)  
						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
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY FS.ReceiptBookId,RBM.Title,FHM.Id,FHM.Title,FHM.OrderIndex
			ORDER BY ReceiptBookId,FHM.Id
	 END
	ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		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
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				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)
				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)
				) 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)  
						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
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY FS.ReceiptBookId,RBM.Title,FS.FeeId,FS.FeeName,FS.OrderIndex
			ORDER BY ReceiptBookId,FS.FeeId
	 END
	ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		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
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				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)
				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)
				) 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)  
						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
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY FS.ReceiptBookId,RBM.Title,CGM.Id,CGM.Title,CGM.OrderIndex
			--ORDER BY ReceiptBookId,CGM.Id
			ORDER BY CGM.OrderIndex
	 END
	END 
  END
ELSE IF(@rType = 2)
		BEGIN
				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 
					(
						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)
						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)
					) 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
							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	
				  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)			
				GROUP BY 
						SA.ClassId,SA.ClassName,SA.OrgId,SA.OrganizationName
				Order By
						SA.ClassId
		END
END
GO
PRINT N'Altering [sFee].[pRptFeePendingDetailListGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeePendingDetailListGet]  

	@rReportId int=0,  
	@rReceiptBookId int=0,
	@rReceiptBookIds nvarchar(max) = '',
	@rAdmissionCategoryId int=0,  
	@rClassId int=0,  
	@rDivisionId int=0,  
	@rUptoDate date='',  
	@rBatchId int=0,  
	@rUserId bigint=0,  
	@rBuilder1 nvarchar(max) = '',  
	@rBuilder2 nvarchar(max) = '',  
	@rIsDetail bit=0,  
	@rOrgId int=0,  
	@rOrgGroupBatchId int=0,  
	@rStatusId int=0,  
	@rCommonBatch nvarchar(100) = '',  
	@rDepartmentId int=0,  
	@rFromRollNo int=0,  
	@rToRollNo int=0,  
	@rCode nvarchar(20)='',  
	@rIsFilter bit=0,  
	@rIsHeader bit=0,    
	@rCreatedUserName nvarchar(20) = '',  
	@rIsReceiptBookGroup bit=0,  
	@rFeeHeadId nvarchar(max) = '',  
	@rIsDisplayOrgGroup bit=0,  
	@rFeeId nvarchar(max) = '',  
	@rFilterId int=0,  
	@rOrgIds  nvarchar(max) = '',  
	@rPayDate date='',  
	@rCollectionGroupId int =0,  
	@rCastCategoryId int = 0,
	@rReportType int=0,
	@rClassStatusId int=0 ,
	@rCollectionGrupId nvarchar(max) ='',
	@rClassIds nvarchar(max) = '',
	@rDivisionIds nvarchar(max) = ''
	 
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 
	
	CREATE TABLE #TempIsOptional
	(
		FeeId int,  
		Id int,  
		IsOptional bit,  
		IsVariable bit,  
		Amount decimal(12,2),  
		StartDate date,  
		EndDate date,  
		BatchId int,  
		ReceiptBookId int,  
		AcademicId bigint,  
		FeeName nvarchar(100),  
		FeeHeadId int,
		CollectionGroupId int,
		CollectionGroup nvarchar(max),
		FeeOrderIndex int
	)
	
	INSERT INTO #TempIsOptional
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup,
			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  
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE   
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))      
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND (FS1.ReceiptBookId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=0)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  

	UNION ALL  

		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup,
			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.tAcademic SA1 ON SA1.Id=FO.SourceId   
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId  
			
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE  
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND (FS1.ReceiptBookId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=1)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')   
	 
	CREATE TABLE #TempReceipt
	(
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint  
	)
	
	INSERT INTO #TempReceipt
	SELECT   
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId  
	FROM  
		sFee.tReceipt R   
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId  
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId     
		AND (SA1.ClassId=@rClassId OR @rClassId=0)   
		AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
		AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
		AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)  
	WHERE    
		(R.SourceTypeId = 2001)  
		AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
		AND (R.IsObsolete = 0)   
		AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))  
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)  
		AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016  
		-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))  
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
		AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
	GROUP BY FeeSetupId,R.SourceId  
	
	CREATE TABLE #TempAssignRoute
	(
		SourceId bigint  
	)
	
	INSERT INTO #TempAssignRoute
	SELECT 
		AT.SourceId 
	FROM 
		sTransport.tAssignRoute AT   
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
	
	IF(@rReportType=1)
	BEGIN	   
		SELECT   
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,  
		@rIsDetail AS IsDetail,  
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		SA.AcademicId,  
		SA.RollNo,  
		SA.Name,  
		SA.Code,  
		SA.ClassId,  
		SA.DivisionId,  
		SA.ClassName,  
		SA.DivisionName,  
		SA.DivisionOrder,  
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		FS.Id AS FeeSetupId,  
		ISNULL(FS.IsVariable,0)AS IsVariable,  
		ISNULL(FS.Amount,0)AS Amount,  
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,  
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,  
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,  
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,  
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,  
		ISNULL(R.PaidAmount,0) AS PaidAmount,  
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,  
		ISNULL(FA.Remark,'') AS Remark,  
		FS.FeeName,  
		FHM.Id AS FeeHeadId,  
		FHM.Title AS FeeHeadName,  
		FHM.OrderIndex AS FeeHeadOrderIndex,  
		SA.OrgId,  
		O.Title AS OrgName,  
		O.OrderIndex AS OrgOrderIndex,  
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0  
		WHEN @rIsReceiptBookGroup = 1 THEN FS.ReceiptBookId  
		END) AS ReceiptBookId,   
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'  
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.Title,'')  
		END) AS ReceiptBookTitle,  
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0  
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.OrderIndex,0)  
		END) AS ReceiptOrderIndex,    
		--FS.ReceiptBookId,  
		ISNULL(RBM.FullTitle,'') AS ReceiptBookFullTitle,
		ISNULL(RBM.Address1,'') AS RecieptBookAddress1,
		IsNULL(RBM.Address2,'') As RecieptBookAddress2,
		IsNULL(RBM.Remark1,'') As Remark1,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
		SA.OrgGroupBatchId,  
		SA.DepartmentId,  
		SA.DepartmentName,  
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,  
		ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark,  
		@rPayDate AS PayDate ,  
		ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId,  
		ISNULL(CCM.Title,'') AS CastCategoryName,  
		ISNULL(CCM.OrderIndex,'') AS CastCategoryOrderIndex,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate  ,
		FS.CollectionGroupId,
		FS.CollectionGroup,
		SA.BatchName,
		ISNULL(SSF.FatherName, '') AS FatherName,
		ISNULL(SSF.FatherContactNo, '') AS FatherContactNo,
		ISNULL(SSF.MotherName, '') AS MotherName,
		ISNULL(SSF.MotherContactNo, '') AS MotherContactNo,
		FS.FeeOrderIndex AS FeeOrderIndex,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
	 SA.GenderId,
	 SA.FirstName as StudentName

	FROM   
		sStudent.vStudentAcademic SA  
		INNER JOIN #TempIsOptional FS ON FS.AcademicId=SA.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA  
		ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId  
		LEFT JOIN #TempReceipt R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId  
		INNER JOIN sSetup.tOrganizationMaster O ON   
		SA.OrgId = O.Id  
		INNER JOIN sFee.tReceiptBookMaster RBM   
		ON FS.ReceiptBookId=RBM.Id  
		LEFT JOIN sStudent.tStudentCommunication SC   
		ON SC.StudentId = SA.StudentId  
		LEFT JOIN sStudent.tStudentOther SO   
		ON SO.StudentId = SA.StudentId  
		LEFT JOIN sCommon.tCastCategoryMaster CCM   
		ON CCM.Id = SO.CastCategoryId    
		INNER JOIN sFee.tFeeHeadMaster FHM  
		ON FHM.Id = FS.FeeHeadId
		
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
		LEFT JOIN #TempAssignRoute RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sStudent.tStudentFamily SSF ON SSF.StudentId = SA .StudentId
	WHERE   
		SA.OrgGroupBatchId = @rOrgGroupBatchId  
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
		AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		AND ((SA.Code=@rCode) OR (@rCode=''))  
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)     
		AND (  
				(@rFilterId = 0) -- All  
				OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
				OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
				OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')       
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0)) 
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	Order by SA.RollNo  
	END
	ELSE
	BEGIN
	SELECT   
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,  
		@rIsDetail AS IsDetail,  
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		SA.AcademicId,  
		SA.RollNo,  
		SA.Name,  
		SA.Code,  
		SA.ClassId,  
		SA.DivisionId,  
		SA.ClassName,  
		SA.DivisionName,  
		SA.DivisionOrder,  
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		FS.Id AS FeeSetupId,  
		ISNULL(FS.IsVariable,0)AS IsVariable,  
		ISNULL(FS.Amount,0)AS Amount,  
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,  
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,  
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,  
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,  
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,  
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0.00) PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,  
		--FS.FeeName,  
		FM.Title AS FeeName,  
		FHM.Id AS FeeHeadId,  
		FHM.Title AS FeeHeadName,  
		FHM.OrderIndex AS FeeHeadOrderIndex,  
		SA.OrgId,  
		O.Title AS OrgName,  
		O.OrderIndex AS OrgOrderIndex,  
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0  
		WHEN @rIsReceiptBookGroup = 1 THEN FS.ReceiptBookId  
		END) AS ReceiptBookId,   
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'  
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.Title,'')  
		END) AS ReceiptBookTitle,  
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0  
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.OrderIndex,0)  
		END) AS ReceiptOrderIndex,    
		ISNULL(FS.ReceiptBookId,'0') As ReceiptBookId,  
		ISNULL(RBM.FullTitle,'') AS ReceiptBookFullTitle,
		ISNULL(RBM.Address1,'') AS RecieptBookAddress1,
		IsNULL(RBM.Address2,'') As RecieptBookAddress2,
		IsNULL(RBM.Remark1,'') As Remark1,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
		SA.OrgGroupBatchId,  
		SA.DepartmentId,  
		SA.DepartmentName,  
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,  
		ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark,  
		@rPayDate AS PayDate ,  
		ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId,  
		ISNULL(CCM.Title,'') AS CastCategoryName,  
		ISNULL(CCM.OrderIndex,'') AS CastCategoryOrderIndex,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		SA.BatchName,
		ISNULL(SSF.FatherName, '') AS FatherName,
		ISNULL(SSF.FatherContactNo, '') AS FatherContactNo,
		ISNULL(SSF.MotherName, '') AS MotherName,
		ISNULL(SSF.MotherContactNo, '') AS MotherContactNo,
		FM.OrderIndex AS FeeOrderIndex,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo
	FROM   
		sStudent.vStudentAcademic SA		
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId	
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FAS.FeeSetupId AND FA.SourceId=SA.AcademicId  
		LEFT JOIN sStudent.tStudentCommunication SC	ON SC.StudentId = SA.StudentId  
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId  
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id 
		AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sStudent.tStudentFamily SSF ON SSF.StudentId = SA .StudentId
	WHERE   
		SA.OrgGroupBatchId = @rOrgGroupBatchId  
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
		AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		AND ((SA.Code=@rCode) OR (@rCode=''))  
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)     
		AND ISNULL(FAS.ToPayAmount,0.00) !=0
		AND (  
				(@rFilterId = 0) -- All  
				OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
				OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
				OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')       
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0))   
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
	Order by SA.RollNo  
	END
	
	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
	DROP TABLE #TempAssignRoute


	
	--SELECT 
	--    '' as Builder1,  
	--	'' as Builder2,  
	--	Convert(bit,0) as IsDetail,  
	--	Convert(bit,0) as IsFilter,  
	--	Convert(bit,0) as IsHeader,  
	--	Convert(bit,0) as IsDisplayOrgGroup,  
	--	0 as AcademicId,  
	--	0 As RollNo,  
	--	'' as Name,  
	--	'' As Code,  
	--	0 as ClassId,  
	--	0 as DivisionId,  
	--	'' as ClassName,  
	--	'' as DivisionName,  
	--	0 as DivisionOrder,  
	--	 '' as ClassDivision,  
	--	0 as FeeSetupId,  
	--	Convert(bit,0) as IsVariable,  
	--	 0.00 As Amount,  
	--	'2001-01-30' AS StartDate,  
	--	'2001-01-30' As EndDate,  
	--	0.00 As FAAmount,  
	--	0.00 As DiscountAmount,  
	--	0.00 As AdditionalAmount,  
	--	0.00 As PaidAmount,
	--	0.00 As  PendingAmount,
	--	'' AS Remark,  
	--	--FS.FeeName,  
	--	'' AS FeeName,  
	--	0 AS FeeHeadId,  
	--	'' AS FeeHeadName,  
	--	0 As FeeHeadOrderIndex,  
	--	0 As OrgId,  
	--	'' AS OrgName,  
	--	0 AS OrgOrderIndex,  
	--	0 AS ReceiptBookId,   
	--	'' AS ReceiptBookTitle,  
	--	0 AS ReceiptOrderIndex,    
	--	'' AS ReceiptBookFullTitle,
	--	'' AS RecieptBookAddress1,
	--	'' AS RecieptBookAddress2,
	--	'' As Remark1,
	--	0 As OrgGroupBatchId,  
	--	0 As DepartmentId,  
	--	'' AS DepartmentName,  
	--	'' AS ParentContactNo,  
	--	'' AS ReferenceRemark,  
	--	'2001-01-30' AS PayDate ,  
	--	0 AS CastCategoryId,  
	--	'' AS CastCategoryName,  
	--	0 AS CastCategoryOrderIndex,
	--	'' AS ReportTemplate,
	--	0 AS CollectionGroupId,
	--	'' AS CollectionGroup,
	--	'' AS BatchName,
	--	'' AS FatherName,
	--	 '' AS FatherContactNo,
	--	 '' AS MotherName,
	--	 '' AS MotherContactNo,
	--	0 AS FeeOrderIndex,
	--	'' AS Address,
	--	'' AS StudentContactNo,
	--    '' as StudentName,
	--	0 As GenderId


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


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

	IF(@rReportType=1)

		BEGIN

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

 
	--CREATE TYPE  TempPendingFee AS TABLE
	--(
	--AcademicId bigint
	--,
	--RollNo int,
	--Name nvarchar(200),
	--Code nvarchar(20),
	--ClassId int,
	--DivisionId int,
	--ClassName nvarchar(100),
	--DivisionName nvarchar(100),
	--ClassDivision nvarchar(100),
	--FeeSetupId int,
	--IsVariable int,
	--Amount Decimal(12,2),
	--StartDate date,
	--EndDate date,
	--FAAmount Decimal(12,2),
	--DiscountAmount Decimal(12,2),
	--AdditionalAmount Decimal(12,2),
	--PaidAmount Decimal(12,2),
	--PendingAmount Decimal(12,2),
	--Remark nvarchar(200),
	--ReceiptBookId int,
	--FeeName nvarchar(100),
	--FeeCode nvarchar(100),
	--OrgId int,
	--OrgName nvarchar(200),
	--OrgOrderIndex int,
	--ReceiptBookTitle nvarchar(200),
	--ReceiptOrderIndex int	
	--)
	
	DECLARE @p as TempPendingFee
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId		,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder
			
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId 
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				GROUP BY FeeSetupId,R.SourceId) R ON R.FeeSetupId = FS.Id 
				AND SA.AcademicId = R.SourceId
		       INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		       INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
			LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
			Order by SA.RollNo

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

END

	ELSE
		BEGIN

	INSERT INTO  @p
SELECT 

		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0) AS PendingAmount,
		--ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FAS.Remark,'') AS Remark,
		FS.ReceiptBookId,
		--FS.FeeName,
		--FS.FeeCode,
		FM.Title AS FeeName, 
		FM.Code AS FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder
  FROM  sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		--LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=SF.FeeSetupId AND FA.SourceId=SA.AcademicId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId 
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND ISNULL(FAS.ToPayAmount,0) !=0
			AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			Order by SA.RollNo

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

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


GO
 

ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
						
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date='',
			@rClassId int = 0,
			@rOrgIds nvarchar(max) = '',
			@rReceiptPrintGroupId nvarchar(100)='',
			@rDivisionId 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
	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,'') = ''))
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
END
GO
PRINT N'Altering [sFee].[pRptFeeRegisterAllStudentListGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeRegisterAllStudentListGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rFromDate date,
		@rToDate date,
		@rFromReceiptNo int,
		@rToReceiptNo int,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsCancel bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsDetail bit=0,
		@rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rPayTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0  

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		SET @rToDate = NULL
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsCancel AS IsCancel,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		R.Id AS ReceiptId,
		(SELECT STUFF    
            (    
                (    
                    SELECT ',' + CONVERT(varchar,R1.ReceiptNumber) FROM sFee.tReceipt R1 
                    LEFT JOIN sFee.tReceiptDetail RD1
						ON RD1.ReceiptId=R1.Id
					LEFT JOIN sFee.tFeeSetup FS1
						ON FS1.Id=RD1.FeeSetupId
					LEFT JOIN sFee.tFeeMaster FM1
						ON FM1.Id=FS1.FeeId     
                    WHERE SA.AcademicId=R1.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) AND   FM1.Code = FM.Code
                    FOR XML PATH('')    
                )    
                    
            ,1,1,'')) as ReceiptNumber,
		--R.ReceiptNumber,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.AcademicId,
		SA.FirstName,
		SA.MiddleName,
		SA.LastName,
		SA.Code,
		SA.Name,
		PTM.Title AS PayType,
		R.ChequeNo,
		R.BankName,
		R.ReceiptAmount,
		R.ReceiptDate,
		FM.Title AS FeeDetail,
		ISNULL(FM.Code,'') AS FeeCode,
		FM.OrderIndex AS FeeOrderIndex,
		(Select SUM(RD1.Amount)AS DetailAmount
			FROM 
				sStudent.vStudentAcademic SA1
				LEFT JOIN sFee.tReceipt R1 
					ON SA1.AcademicId=R1.SourceId AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				LEFT JOIN sFee.tReceiptDetail RD1
					ON RD1.ReceiptId=R1.Id
				LEFT JOIN sFee.tFeeSetup FS1
					ON FS1.Id=RD1.FeeSetupId
				LEFT JOIN sFee.tFeeMaster FM1
					ON FM1.Id=FS1.FeeId
					WHERE SA.AcademicId = R1.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) AND FM1.Code =FM.Code) AS DetailAmount,
		--RD.Amount AS DetailAmount,
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		ISNULL(FHM.Title,'') AS FeeHead,
		ISNULL(FHM.Code,'') AS FeeHeadCode,
		ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(R.Remark,'') AS Remark,
		DM.Id AS DepartmentId,
		DM.Title AS DepartmentName,
		SA.ClassOrderIndex,
		ISNULL(SO.GenderId,0) AS GenderId,
		ISNULL(SA.BatchName,'') BatchName,
		ISNULL(FM.FeeHeadId,0) AS FeeHeadId,
		sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,
		R.ChequeDate
  FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sFee.tReceipt R 
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		LEFT JOIN sFee.tReceiptDetail RD
			ON RD.ReceiptId=R.Id
		LEFT JOIN sFee.tFeeSetup FS
			ON FS.Id=RD.FeeSetupId
		LEFT JOIN sFee.tFeeMaster FM
			ON FM.Id=FS.FeeId
		LEFT JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tDepartmentMaster DM
			ON SA.DepartmentId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster O
			ON O.Id=SA.OrgId
		LEFT JOIN sSecurity.tUser U
			ON U.Id=R.CreatedUserId
		LEFT JOIN sStudent.tStudentOther SO
			ON SO.StudentId = SA.StudentId
	   LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
      LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
				
WHERE 
	--R.SourceTypeId = 2001
	--AND	
	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	--AND (R.IsObsolete = @rIsCancel) 
	AND (SA.StatusId = @rStatusId OR @rStatusId=0)
	AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))
	AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
     AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	ORDER BY R.ReceiptNumber
END
GO
PRINT N'Altering [sFrontOffice].[pVisitorLogGet]...';


GO
ALTER PROCEDURE [sFrontOffice].[pVisitorLogGet]
          
           @rVisitorId int=0,
           --@rOutTimeFrom datetime,
           --@rOutTimeTo datetime,
           @rFromVisitDate datetime,
           @rToVisitDate datetime,
           @rOrgId int=0,
           @rWhomToMeetName nvarchar(100)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int =0,
           @rTypeId int=0 ,
		   @rStatusId int=0 
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rWhomToMeetName = sCommon.fSearchStringGet(@rWhomToMeetName)
		--END
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId


BEGIN
SELECT  
	   VL.Id As VisitorId,
       VL.VisitorName,
       VL.NoOfVisitor,
       VL.PurposeOfVisit,
       VL.WhomToMeet AS WhomToMeetId,
	   (isnull(case when isnull(VL.WhomToMeet,0)!=0 then isnull(EM.EmployeeName,'') else ISNULL(VL.WhomToMeetName,'') end,'' )
	   --+ (case when isnull(VL.StudentId,0)!=0 AND isnull(VL.WhomToMeet,0)!=0 then ',' else '' end)
	   --+isnull(case when  isnull(VL.StudentId,0)!=0 Then sStudent.fStudentNameGet(STM.FirstName, STM.MiddleName,STM.LastName, OM1.StudentNameFormatId) end,'')
	   ) AS WhomToMeetName,
	   ISNULL(VL.InTime,'00:00') AS InTime,
       ISNULL(VL.OutTime,'00:00') AS OutTime,
       ISNULL(VL.VisitDate,'1900-01-01 00:00:00') AS VisitDate,
       --VL.CreatedDateTime ,
       (CASE  WHEN @rIsPrintView=1 THEN 
				VL.VisitorPhoto		
			ELSE ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
       --ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
       VL.OrgId,
       ISNULL(OM.DisplayTitle,'') AS Organization,
       ISNULL(Remark,'') AS Remark,
       @GatePassConfig AS ConfigValue,
	   ISNUll(VisitorContactNumber,'') AS VisitorContactNumber,
	   ISNULL(StudentId,0) AS StudentId,
	   (CASE WHEN ISNULL(VL.TypeId,'')!='' then case when VL.TypeId=1 then 'Visitor' else 'Parents' end
			 when ISNULL(VL.StudentId,0)=0 THEN 'Visitor'
			 ELSE 'Parents' END) AS VisitorType,
	   (CASE WHEN ISNULL(VL.OutTime,'00:00:00')='00:00:00' THEN 0
			 ELSE 1 END) AS InOutStatus,
		OM.OrgGroupId AS OrgGroupId,
		SM.Title as Status,
		ISNULL(VL.StatusId,0) as StatusId,
		(CASE WHEN ISNULL(VL.TypeId,'')!='' then case when VL.TypeId=1 then 1 else 2 end
			 when ISNULL(VL.StudentId,0)=0 THEN 1
			 ELSE 2 END) AS VisitorTypeId
		
  FROM  sFrontOffice.tVisitorLog VL 
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId
  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = VL.StatusId
  Left Join  sHrm.vExtEmployeeMaster EM on EM.EmployeeId=VL.WhomToMeet
  left Join sStudent.tStudentMaster STM On STM.Id=VL.StudentId  
  left JOIN sSetup.tOrganizationMaster AS OM1 ON STM.OrgId = OM1.Id 
 
  WHERE 
	(VL.OrgId=@rOrgId OR @rOrgId=0) AND OM.OrgGroupId=@rOrgGroupId
	AND (VL.Id=@rVisitorId OR @rVisitorId=0)
	AND (((VL.WhomToMeetName LIKE @rWhomToMeetName) OR  (isnull(EM.EmployeeId,0)>0 AND EM.EmployeeName Like  @rWhomToMeetName) OR (isnull(STM.Id,0)>0 AND sStudent.fStudentNameGet(STM.FirstName, STM.MiddleName,STM.LastName, OM1.StudentNameFormatId) like  @rWhomToMeetName)) OR (ISNULL(@rWhomToMeetName,'')=''))
	AND (VL.VisitDate>=@rFromVisitDate OR ISNULL(@rFromVisitDate,'')='')
	AND (VL.VisitDate<=@rToVisitDate OR ISNULL(@rToVisitDate,'')='')
	AND ((ISNULL(VL.TypeId,0)=0 AND (ISNULL(VL.StudentId,1) = @rTypeId) OR  (@rTypeId=0) OR (((VL.StudentId > 0 AND @rTypeId=2) OR  @rTypeId=0)))  OR (ISNULL(VL.TypeId,0)!=0 AND ((VL.TypeId=@rTypeId) or (@rTypeId=0)))) -- Visitor 
	AND ((VL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0)) 
	 -- Parents
  ORDER BY VL.VisitDate DESC,VL.InTime DESC
END
GO
PRINT N'Altering [sRecruitment].[pVacancyMasterGet]...';


GO
 
ALTER PROCEDURE [sRecruitment].[pVacancyMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),	
	 @rOrgGroupId smallint,
	 @rIsSearch bit = 1
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
CREATE TABLE #TotalCandidate (
VacancyId BigInt,
TotalAppliedCandidate Int
)
INSERT INTO #TotalCandidate (VacancyId,TotalAppliedCandidate)
SELECT VacancyId ,Count(Id) as TotalAppliedCandidate From [sRecruitment].[tCandidateMaster] Group By VacancyId;

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			VM.Id,
			VM.Title,
			VM.TotalVacancy,
		    VM.MinimumQualification, 
		    VM.Subjects, 
		    VM.Experience, 
		    VM.IsClose, 
		    VM.CreatedDateTime,
		    VM.KeySkills,
		    VM.QualificationFor,
		    VM.ConfirmationRemark,
			ISNULL(VM.FormRemark,'') AS FormRemark,
            ISNULL(TC.TotalAppliedCandidate,0) AS TotalAppliedCandidate
      
  FROM 
            sRecruitment.tVacancy VM LEFT JOIN #TotalCandidate TC ON TC.VacancyId = VM.Id
            
            
  WHERE   
           ((VM.Id = @rId) OR (@rId = 0))
	       AND ((VM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	   AND VM.OrgGroupId=@rOrgGroupId
	    
	      order by Id desc
 
 DROP TABLE #TotalCandidate
END
GO
PRINT N'Altering [sSecurity].[pAppPermissionGet]...';


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

	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard 
			20097, -- View Query
			30249, -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786, --Online Learning 
			30787, --Online learning Student View
			30815, --Consolidate - Fee Status
			30813, --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,   -- Consolidate - Admission Inquiry Summary,
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App 
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,   -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,   -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008,  -- Is CS Entry View
			31009,  -- Is Activity Entry View
			20556,  -- Hostel Student Gate Pass
			31005,	-- My Digital Form
			20183, -- View Photo
			30580, -- Employee Attendance Summary
			20056, -- Event Schedule
			31033, --My Proxy
			20687, --  Employee Attendance
			31043 --  Pending Fee
			,30943 -- My Approval Request
			,30739 -- Behaviour Entry User Wise
			,31048 -- Add Gallery
			,31175 -- View Gallery
			,31179 -- Leave Hierarchy Listing
			,30331 -- My Exam Schedule
			,31182 -- My Admit Card
			)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard
			20097, -- View Query
			30249,  -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786 , --Online Learning 
			30787,  --Online learning Student View
			30815,  --Consolidate - Fee Status
			30813,  --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,  -- Consolidate - Admission Inquiry Summary
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,    -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance			
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,    -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008,  -- Is CS Entry View
			31009,   -- Is Activity Entry View
			20556,   -- Hostel Student Gate Pass
			31005,	-- My Digital Form
			20183, -- View Photo
			30580, -- Employee Attendance Summary
			20056, -- Event Schedule
			31033, --My Proxy
			20687, --  Employee Attendance
			31043 --  Pending Fee
			,30943 -- My Approval Request
			,30739 -- Behaviour Entry User Wise
			,31048 -- Add Gallery
			,31175 -- View Gallery
			,31179 -- Leave Hierarchy Listing
			,30331 -- My Exam Schedule
			,31182 -- My Admit Card
			) 
		) TP 
		GROUP BY TP.TaskId
	END
END
GO
PRINT N'Altering [sSecurity].[pScreenGroupDataListGet]...';


GO

 
ALTER PROCEDURE [sSecurity].[pScreenGroupDataListGet]

	@rUserId [bigint]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

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

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

END
GO
PRINT N'Altering [sStudent].[pStudentDataModify]...';


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

--BEGIN TRY
--BEGIN TRANSACTION

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

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

		set @sql='UPDATE sStudent.tStudentAdmission set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentAdmission SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'AdmissionDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdmission SET '+@rSubCategoryField+' = null WHERE AdmissionDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'PreviousLCDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdmission SET '+@rSubCategoryField+' = null WHERE PreviousLCDate=''1900-01-01'''
			Exec sp_executesql @sql
		END

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

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

		set @sql='INSERT INTO sStudent.tStudentAdditional
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentAdditional set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentAdditional SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
					
		Exec sp_executesql @sql
					
		IF(@rSubCategoryField = 'PassportIssueDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdditional SET '+@rSubCategoryField+' = null WHERE PassportIssueDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'PassportExpiryDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdditional SET '+@rSubCategoryField+' = null WHERE PassportExpiryDate=''1900-01-01'''
			Exec sp_executesql @sql
		END						
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	     
	 Else IF(@rCategoryId= 9)
	    BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(200)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
		set @sql='INSERT INTO sStudent.tStudentSibling
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentSibling set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentSibling SS 
					INNER JOIN ListofData LD ON SS.StudentId=LD.StudentId AND IsExist=0'
					
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
GO
PRINT N'Altering [sStudent].[pStudentSearchWithPhotoGet]...';


GO
 
 
ALTER PROCEDURE [sStudent].[pStudentSearchWithPhotoGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int,
    @rSUId nvarchar(20)='',
    @rUserId bigint=0,
	@rClassStatusId smallint = 0,
	@rContactNo nvarchar(50) = ''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			ISNULL(SA.SUId,'') AS SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			SA.ClassStatusId,
			SA.ClassStatusName
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
	   LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
	   LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		--AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		AND ((SC.PresentContactNo=@rContactNo) OR (SC.PermanentContactNo=@rContactNo) OR (SC.EmergencyContactNo=@rContactNo) OR (SC.ParentContactNo=@rContactNo) OR (SC.StudentContactNo=@rContactNo) OR (SF.FatherContactNo=@rContactNo) OR (SF.MotherContactNo=@rContactNo) OR (@rContactNo=''))
ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			ISNULL(SA.SUId,'') AS SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			SA.ClassStatusId,
			SA.ClassStatusName
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
	   LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
	   LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)	
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		--AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND ((SC.PresentContactNo=@rContactNo) OR (SC.PermanentContactNo=@rContactNo) OR (SC.EmergencyContactNo=@rContactNo) OR (SC.ParentContactno=@rContactNo) OR (SC.StudentContactNo=@rContactNo) OR (SF.FatherContactNo=@rContactNo) OR (SF.MotherContactNo=@rContactNo) OR (@rContactNo=''))

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
  
		
END
GO
PRINT N'Altering [sTimetable].[pRptFreeTeacherTimetableGet]...';


GO
 
ALTER PROCEDURE [sTimetable].[pRptFreeTeacherTimetableGet]

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

BEGIN   
 
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	 
	CASE WHEN A.TimeTableID is not null THEN ISNULL(A.Subject,'FREE') ELSE '' END AS Subject,
	--CASE WHEN A.EmployeeId=-1 THEN 'FREE' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	--CASE WHEN A.SubjectId=-1 THEN 'FREE' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--ELSE
	 A.EmployeeName AS EmployeeName,
	--CASE WHEN A.EmployeeId=0 THEN 'Free' ELSE '' END AS Subject,
	 
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	'' AS ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code ,
	 case WHEN A.TimeTableID is not null THEN ISNULL(A.ClassSubject,'FREE') ELSE '' END  AS ClassSubject
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(STUFF((
		SELECT '/ ' +  ISNULL(SM1.Title,'')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 1, ''),'') ClassSubject
	
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
	WHERE  1=1
	AND (ClassId = @rClassId OR @rClassId=0)
	AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (DV.OrgId = @rOrgId OR @rOrgId = 0)
	  --ORDER BY DV.OrderIndex
	  )
	  A
			--RIGHT JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			--INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			--WHERE TimeTableSchemaId=@rTimeTableSchemaId ) L
			--ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId
		 
END
GO
PRINT N'Altering [sTimetable].[pTimeTableAdd]...';


GO

ALTER PROCEDURE [sTimetable].[pTimeTableAdd]
		
		@rOrgId int,
		@rId int,
		@rTimeTableSchemaID int,
		@rEmployeeId bigint,
		@rDivisionId int,
		@rSubjectId int,
		@rDayId smallint,
		@rLectureNumber smallint,
		@rLockNo bigint,
		@rLockColour varchar(50)
		
		
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 
 
BEGIN 

	 BEGIN TRY	
	 BEGIN TRANSACTION 
	   print 'a'
	IF NOT EXISTS(Select 1 FROM sTimetable.tTimeTable Where EmployeeId = @rEmployeeId AND SubjectId=@rSubjectId  AND  LectureNumber = @rLectureNumber AND DayId = @rDayId and TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId=@rDivisionId )
	 
	BEGIN
	IF NOT EXISTS(Select 1 FROM sTimetable.tTimeTable Where  SubjectId=@rSubjectId  AND LectureNumber = @rLectureNumber AND DayId = @rDayId and TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId=@rDivisionId)
	BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tTimeTable', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	 
	  BEGIN
		   INSERT INTO sTimetable.tTimeTable		 
		   (
				[Id]
			   ,[TimeTableSchemaId]
			   ,[EmployeeId]
			   ,[DivisionId]
			   ,[SubjectId]
			   ,[DayId]
			   ,[LectureNumber]
			   ,[LockNo]
			   ,[LockColour]
            )		 
			VALUES
			(	
				@lNextNumber,
				@rTimeTableSchemaID,
				@rEmployeeId,
				@rDivisionId,
				@rSubjectId,
				@rDayId,
				@rLectureNumber,
				@rLockNo,
				@rLockColour
			)		
			SELECT @lNextNumber AS Result
    	END
      END
	  ELSE
	  BEGIN       
		  SELECT -102 AS Result
		END
	  END
    ELSE
    BEGIN       
      SELECT -101 AS Result
    END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	
END 	             
	
		
END
GO
PRINT N'Creating [sAlert].[pEmployeeBiometricFirstInTimeGet]...';


GO

CREATE PROCEDURE [sAlert].[pEmployeeBiometricFirstInTimeGet]
	 	 @rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)='',
		@rOrgId int,
		@rIntervalTime int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			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
				)
			insert into #tTable
			select SourceId,min(In_Out_Time),SourceTypeId 
			from [sBiometric].[tCloudTransactionData] 
			WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]()) AND SourceTypeId=95 Group by SourceId,SourceTypeId
	
			--select * from #tTable

			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				replace (
				replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS EmployeeName,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId
			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.In_Out_Time >= DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]())
				AND EM.OrgID =@rOrgId

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


END
GO
PRINT N'Creating [sAlert].[pEmployeeBiometricLastOutTimeGet]...';


GO

CREATE PROCEDURE [sAlert].[pEmployeeBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(10)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int
 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL,
					Interval int not NUll
				)
			insert #tShift
			Select 
				ShiftCode, 
				case When DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime then DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) else @rIntervalTime end 
			  FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			AND IsOutTimeAlertTime=1
			AND CAST(OutTimeAlertTime AS Time)<cast([sCommon].[fGetDate]() as Time)

			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,
						Interval int NOT NULL
					)
			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,tempShift.Interval
				from [sBiometric].[tCloudTransactionData] CDT 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 Group by SourceId,SourceTypeId,tempShift.Interval
			END

			--select * from #tTable

			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				replace (
				replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS EmployeeName,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId
			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.In_Out_Time >= DATEADD(minute,-(temp.Interval),[sCommon].[fGetDate]())
				AND EM.OrgID =@rOrgId

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


GO

CREATE PROCEDURE [sAlert].[pStudentBiometricFirstInTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rIntervalTime int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			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,

				)
			insert into #tTable
			select SourceId,min(In_Out_Time),SourceTypeId 
			from [sBiometric].[tCloudTransactionData] 
			WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 Group by SourceId,SourceTypeId
	
			--select * from #tTable
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				replace (
				replace(@rTemplate,'[StudentName]',SC.Name),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS EmployeeName,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId


			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.In_Out_Time >= DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]())
				AND SC.OrgID =@rOrgId
				AND SC.StatusId = 1
			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH

END
GO
PRINT N'Creating [sAlert].[pStudentBiometricLastOutTimeGet]...';


GO

CREATE PROCEDURE [sAlert].[pStudentBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

			insert #tShift
			Select 
				ShiftCode, 
				case When DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime then DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) else @rIntervalTime end 
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			AND IsOutTimeAlertTime=1
			AND CAST(OutTimeAlertTime AS Time)<cast([sCommon].[fGetDate]() 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,
				Interval int NOT NULL
			)
			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,tempShift.Interval 
				from [sBiometric].[tCloudTransactionData] CDT 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 Group by SourceId,SourceTypeId,tempShift.Interval
			End
			--select * from #tTable

			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				replace (
				replace(@rTemplate,'[StudentName]',SC.Name),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS EmployeeName,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId


			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.In_Out_Time >= DATEADD(minute,-(temp.Interval),[sCommon].[fGetDate]())
				AND SC.OrgID =@rOrgId
				AND SC.StatusId = 1

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sFee].[pChargeReceiptDeletedLog]...';


GO
CREATE PROCEDURE [sFee].[pChargeReceiptDeletedLog]

	 @rChargeReceiptId bigint,
	 @rUserId bigint=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
	BEGIN TRANSACTION	
		--Charge Receipt Delete
		INSERT INTO 
			sAudit.tChargeDeleted 
		SELECT 
			CR.OrgId,
			Id,
			SA.Code,
			SourceTypeId,
			SourceId,
			SA.FirstName + ' ' + SA.MiddleName + ' ' + SA.LastName AS SourceName,
			Remark,
			ReceiptNumber,
			ReceiptDate,
			PayTypeId,
			ChequeNo,
			BankName,
			IsObsolete,
			CR.BatchId,
			(select Title from sFee.tChargeReceiptBookMaster CB where CB.Id=CR.ChargeReceiptBookId) AS ChargeReceiptBookName,			
			CR.OrgGroupBatchId,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id=CR.CreatedUserId),
			CreatedDateTime,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id=CR.CreatedUserId),
			UpdatedDateTime,		
			ReceiptAmount,
			ChequeDate,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id=@rUserId),
			sCommon.fGetDate()
		FROM 
			sFee.tChargeReceipt CR
			INNER join sStudent.vStudentAcademic SA ON CR.SourceId=SA.AcademicId
		WHERE 
			Id=@rChargeReceiptId 
		
		-- Charge Receipt Detail Delete
		INSERT INTO 
			sAudit.tChargeDetailDelete 
		SELECT
			ChargeReceiptId,
			CM.Title,
			Amount
		FROM
			sFee.tChargeReceipt CR 
			INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id 
			INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId 
			INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		WHERE 
			ChargeReceiptId=@rChargeReceiptId
		
		SELECT 1 AS Result
		
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, Error_message(),Error_line()
	END CATCH	
END
GO
PRINT N'Creating [sFee].[pExportChargeReceiptDeletedLog]...';


GO
CREATE PROCEDURE [sFee].[pExportChargeReceiptDeletedLog]

	 @rOrgGroupBatchId bigint,
	 @rOrgId bigint=0,
	 @rFromDate date=NULL,
	 @rToDate date=NULL
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
		CD.Code,
		GuestName As SourceName,
		ReceiptNumber,			
		convert(varchar(10), ReceiptDate, 103) As ReceiptDate,
		ReceiptAmount,
		PayTypeId As PayType,
		ChequeNo,
		BankName,
		ChargeReceiptBookName,
		Remark,
		CreatedUser,				
           convert(varchar(10),CreatedDateTime, 103) + right(convert(varchar(32),CreatedDateTime,100),8) As CreatedDateTime,	 		
		DeletededUser,			
		convert(varchar(10),DeletedDateTime, 103) + right(convert(varchar(32),DeletedDateTime,100),8) As DeletedDateTime,	 
		(SELECT DISTINCT
		 STUFF((SELECT ',' + U.ChargeName + '-' + CONVERT(varchar(10), U.Amount) 
				FROM sAudit.tChargeDetailDelete U
				WHERE U.ChargeName = ChargeName And  ChargeReceiptId=CD.Id
				ORDER BY U.ChargeName FOR XML PATH('')),1,1,''
				) AS ChargeReceiptDetailDeletelist
	     FROM sAudit.tChargeDetailDelete GROUP BY ChargeReceiptId
	     ) AS DeletedChargeReceiptDetail
	FROM 
	   sAudit.tChargeDeleted  CD
	   INNER JOIN sStudent.vStudentAcademic SA ON CD.SourceId=SA.AcademicId
	WHERE 
	   SA.OrgGroupBatchId =@rOrgGroupBatchId
	   AND ((SA.OrgId=@rOrgId) OR (@rOrgId = 0))
	   AND ((CD.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	   AND ((CD.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	ORDER BY CD.ReceiptDate DESC    
END
GO
PRINT N'Creating [sSecurity].[pEmailValidateUser]...';


GO
CREATE PROCEDURE [sSecurity].[pEmailValidateUser]

    @rOrgId int = 0,
    @rUserTitle nvarchar(100)='',
    @rUserEmailId nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		DECLARE @rUserSourceId bigint=0
		DECLARE @rUserId bigint=0
		DECLARE @rUserSourceTypeId smallint=0
		DECLARE @newpwd VARCHAR(100)
		SELECT @rUserId=Id,@rUserSourceId = SourceId,@rUserSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND OrgId = @rOrgId
		
		IF(@rUserSourceTypeId = 95)
		BEGIN
			IF EXISTS (SELECT 1 FROM sHrm.tEmployeeCommunications WHERE CompanyEmail = @rUserEmailId and EmployeeId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				
					EXEC [sSecurity].[pNumericOTPGenerate] @len=4, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId

					SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Email Id is wrong' AS [Message],'' AS OTP
			END	
		END
		IF(@rUserSourceTypeId = 2003)
		BEGIN
			IF EXISTS (SELECT 1 FROM sStudent.tStudentCommunication WHERE ParentEmail = @rUserEmailId and StudentId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				
					EXEC [sSecurity].[pNumericOTPGenerate] @len=4, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId
					SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId  AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Email Id is wrong' AS [Message],'' AS OTP
			END		
		END
		ELSE
		BEGIN
			SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
		END
END
GO
 
  


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