GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('17.09.02',170902,'BEGIN','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO
 
GO
PRINT N'Altering [dbo].[TempTableForProgress]...';


GO
ALTER TABLE [dbo].[TempTableForProgress]
    ADD [EXAMNAME] NVARCHAR (50) NULL;


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


GO
ALTER TABLE [sAssessment].[tTempAllExamSubjectActivity]
    ADD [TeacherSignCaption]   NVARCHAR (100) NULL,
        [PrincipalSignCaption] NVARCHAR (100) NULL,
        [ParentSignCaption]    NVARCHAR (100) NULL;


GO
PRINT N'Altering [sAttendance].[tTempAttendance]...';


GO
ALTER TABLE [sAttendance].[tTempAttendance]
    ADD [DateOfBirth] DATE           NULL,
        [Religion]    NVARCHAR (50)  NULL,
        [MotherName]  NVARCHAR (50)  NULL,
        [FamilyCast]  NVARCHAR (100) NULL;


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


GO
ALTER TABLE [sFee].[tAccountPosting]
    ADD [ChequeNo] NCHAR (10)    NULL,
        [BankName] NVARCHAR (50) NULL;


GO
PRINT N'Altering [sHostel].[tHostelDepositAdd]...';


GO
ALTER TABLE [sHostel].[tHostelDepositAdd]
    ADD [PreviousBalance] DECIMAL (12, 2) NULL;


GO
PRINT N'Altering [sSecurity].[tUserLog]...';


GO
ALTER TABLE [sSecurity].[tUserLog]
    ADD [LoggedInLocalIp] NVARCHAR (100) NULL;


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


GO
ALTER TABLE [sStudent].[tStudentCustomSearch]
    ADD [FeeExemption] NVARCHAR (MAX) NULL;


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


GO
CREATE TABLE [dbo].[StudentPortalTemp] (
    [StudentId] BIGINT        NOT NULL,
    [Number]    NVARCHAR (50) NULL,
    [OrgId]     INT           NULL
);


GO
PRINT N'Creating [sBiometric].[tEmployeeLateStatus]...';


GO
CREATE TABLE [sBiometric].[tEmployeeLateStatus] (
    [Id]              INT           IDENTITY (1, 1) NOT NULL,
    [EmployeeId]      BIGINT        NULL,
    [LateDate]        DATETIME      NULL,
    [LateStatus]      NVARCHAR (10) NULL,
    [IsApproved]      BIT           NULL,
    [CreatedUserId]   BIGINT        NOT NULL,
    [CreatedDateTime] DATETIME      NOT NULL,
    [UpdatedUserId]   BIGINT        NULL,
    [UpdatedDateTime] DATETIME      NULL
);


GO
PRINT N'Creating PK_tEmployeeLateStatus...';


GO
ALTER TABLE [sBiometric].[tEmployeeLateStatus]
    ADD CONSTRAINT [PK_tEmployeeLateStatus] 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 [sCommunication].[tFeedback]...';


GO
CREATE TABLE [sCommunication].[tFeedback] (
    [Id]                 BIGINT         NOT NULL,
    [Title]              NVARCHAR (200) NOT NULL,
    [FeedbackTemplateId] BIGINT         NOT NULL,
    [IsPublish]          BIT            NOT NULL,
    [IsClose]            BIT            NOT NULL,
    [OrgGroupBatchId]    INT            NOT NULL,
    [CreatedUserId]      BIGINT         NOT NULL,
    [CreatedDateTime]    DATETIME       NOT NULL,
    [UpdatedUserId]      BIGINT         NULL,
    [UpdatedDateTime]    DATETIME       NULL
);


GO
PRINT N'Creating PK_tFeedback...';


GO
ALTER TABLE [sCommunication].[tFeedback]
    ADD CONSTRAINT [PK_tFeedback] 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 [sCommunication].[tFeedBackAnswerGroupMaster]...';


GO
CREATE TABLE [sCommunication].[tFeedBackAnswerGroupMaster] (
    [Id]         INT            NOT NULL,
    [Code]       NVARCHAR (100) NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL
);


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


GO
CREATE TABLE [sCommunication].[tFeedbackAnswerTypeDetail] (
    [Id]                   BIGINT         NOT NULL,
    [FeedbackAnswerTypeId] BIGINT         NOT NULL,
    [Title]                NVARCHAR (200) NOT NULL
);


GO
PRINT N'Creating PK_tAnswerTypeDetail...';


GO
ALTER TABLE [sCommunication].[tFeedbackAnswerTypeDetail]
    ADD CONSTRAINT [PK_tAnswerTypeDetail] 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 [sCommunication].[tFeedbackAnswerTypeMaster]...';


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


GO
PRINT N'Creating PK_tAnswerTypeMaster...';


GO
ALTER TABLE [sCommunication].[tFeedbackAnswerTypeMaster]
    ADD CONSTRAINT [PK_tAnswerTypeMaster] 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 [sCommunication].[tFeedbackAssign]...';


GO
CREATE TABLE [sCommunication].[tFeedbackAssign] (
    [Id]                   BIGINT         IDENTITY (1, 1) NOT NULL,
    [AssignToSourceTypeId] SMALLINT       NOT NULL,
    [AssignToSourceId]     BIGINT         NOT NULL,
    [FeedbackId]           BIGINT         NOT NULL,
    [ForName]              NVARCHAR (200) NULL
);


GO
PRINT N'Creating PK_tFeedbackAssign...';


GO
ALTER TABLE [sCommunication].[tFeedbackAssign]
    ADD CONSTRAINT [PK_tFeedbackAssign] 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 [sCommunication].[tFeedbackFor]...';


GO
CREATE TABLE [sCommunication].[tFeedbackFor] (
    [Id]              BIGINT         IDENTITY (1, 1) NOT NULL,
    [ForSourceTypeId] SMALLINT       NOT NULL,
    [ForSourceId]     BIGINT         NOT NULL,
    [FeedbackId]      BIGINT         NOT NULL,
    [ForName]         NVARCHAR (200) NULL
);


GO
PRINT N'Creating PK_tFeedbackFor...';


GO
ALTER TABLE [sCommunication].[tFeedbackFor]
    ADD CONSTRAINT [PK_tFeedbackFor] 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 [sCommunication].[tFeedbackQuestionResponse]...';


GO
CREATE TABLE [sCommunication].[tFeedbackQuestionResponse] (
    [Id]                         BIGINT         IDENTITY (1, 1) NOT NULL,
    [FeedbackResponseId]         BIGINT         NOT NULL,
    [FeedbackTemplateQuestionId] BIGINT         NOT NULL,
    [FeedbackAnswerTypeDetailId] BIGINT         NOT NULL,
    [FeedbackAnswerDescription]  NVARCHAR (200) NULL
);


GO
PRINT N'Creating PK_tFeedBackQuestionResponse...';


GO
ALTER TABLE [sCommunication].[tFeedbackQuestionResponse]
    ADD CONSTRAINT [PK_tFeedBackQuestionResponse] 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 [sCommunication].[tFeedbackResponse]...';


GO
CREATE TABLE [sCommunication].[tFeedbackResponse] (
    [Id]              BIGINT   NOT NULL,
    [FeedbackId]      BIGINT   NOT NULL,
    [SourceTypeId]    SMALLINT NOT NULL,
    [SourceId]        BIGINT   NOT NULL,
    [CreatedUserId]   BIGINT   NOT NULL,
    [CreatedDateTime] DATETIME NOT NULL,
    [UpdatedUserId]   BIGINT   NULL,
    [UpdatedDateTime] DATETIME NULL
);


GO
PRINT N'Creating PK_tFeedBackResponse...';


GO
ALTER TABLE [sCommunication].[tFeedbackResponse]
    ADD CONSTRAINT [PK_tFeedBackResponse] 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 [sCommunication].[tFeedbackTemplate]...';


GO
CREATE TABLE [sCommunication].[tFeedbackTemplate] (
    [Id]              BIGINT         NOT NULL,
    [Code]            NVARCHAR (100) NOT NULL,
    [Title]           NVARCHAR (200) NOT NULL,
    [OrgGroupId]      SMALLINT       NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);


GO
PRINT N'Creating PK_tFeedBackTemplate...';


GO
ALTER TABLE [sCommunication].[tFeedbackTemplate]
    ADD CONSTRAINT [PK_tFeedBackTemplate] 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 [sCommunication].[tFeedbackTemplateQuestion]...';


GO
CREATE TABLE [sCommunication].[tFeedbackTemplateQuestion] (
    [Id]                   BIGINT         NOT NULL,
    [QuestionNumber]       INT            NOT NULL,
    [Question]             NVARCHAR (200) NOT NULL,
    [FeedbackTemplateId]   BIGINT         NOT NULL,
    [FeedbackAnswerTypeId] BIGINT         NOT NULL,
    [CreatedUserId]        BIGINT         NOT NULL,
    [CreatedDateTime]      DATETIME       NOT NULL,
    [UpdatedUserId]        BIGINT         NULL,
    [UpdatedDateTime]      DATETIME       NULL
);


GO
PRINT N'Creating PK_tFeedBackTemplateQuestion...';


GO
ALTER TABLE [sCommunication].[tFeedbackTemplateQuestion]
    ADD CONSTRAINT [PK_tFeedBackTemplateQuestion] 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 [sProcurement].[tStockReset]...';


GO
CREATE TABLE [sProcurement].[tStockReset] (
    [Id]                BIGINT         NOT NULL,
    [Number]            NVARCHAR (20)  NOT NULL,
    [ResetByName]       NVARCHAR (100) NOT NULL,
    [ToStoreLocationId] INT            NOT NULL,
    [Remark]            NVARCHAR (300) NULL,
    [CreatedUserId]     BIGINT         NOT NULL,
    [CreatedDateTime]   DATETIME       NOT NULL,
    [OrgGroupId]        SMALLINT       NOT NULL
);


GO
PRINT N'Creating PK_tStockReset...';


GO
ALTER TABLE [sProcurement].[tStockReset]
    ADD CONSTRAINT [PK_tStockReset] 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 [sProcurement].[tStockResetBatch]...';


GO
CREATE TABLE [sProcurement].[tStockResetBatch] (
    [Id]           BIGINT          NOT NULL,
    [StockResetId] BIGINT          NOT NULL,
    [Quantity]     DECIMAL (12, 2) NOT NULL,
    [StockBatchId] INT             NOT NULL,
    [OrgGroupId]   SMALLINT        NOT NULL,
    [UnitCost]     DECIMAL (12, 2) NULL
);


GO
PRINT N'Creating PK_tStockResetBatch...';


GO
ALTER TABLE [sProcurement].[tStockResetBatch]
    ADD CONSTRAINT [PK_tStockResetBatch] 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 [sStudent].[tTempStudent11]...';


GO
CREATE TABLE [sStudent].[tTempStudent11] (
    [StudentId6] INT NULL
);


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


GO
CREATE TABLE [sSystem].[tBackupLog] (
    [AutoId]         BIGINT         IDENTITY (1, 1) NOT NULL,
    [BackupDateTime] DATETIME       NULL,
    [BackupPath]     NVARCHAR (200) NULL,
    [VersionId]      BIGINT         NULL,
    [CreatedUserId]  BIGINT         NULL
);


GO
PRINT N'Creating PK_tBackupLog...';


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


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


GO
CREATE TABLE [sSystem].[tPortalSync] (
    [OrgGroupId] SMALLINT NOT NULL,
    [FeeChange]  BIT      NULL
);


GO
PRINT N'Creating PK_tPortalSync...';


GO
ALTER TABLE [sSystem].[tPortalSync]
    ADD CONSTRAINT [PK_tPortalSync] PRIMARY KEY CLUSTERED ([OrgGroupId] 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_tStaticVersion...';


GO
ALTER TABLE [sSystem].[tStaticVersion]
    ADD CONSTRAINT [PK_tStaticVersion] PRIMARY KEY CLUSTERED ([VersionId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO

GO
PRINT N'Altering [sAttendance].[fAttendanceAdmissionDateGet]...';


GO
 
ALTER FUNCTION [sAttendance].[fAttendanceAdmissionDateGet]( @rAdmissionDate date,@rAttendanceDate nvarchar(20),@rLeftDate date,@rStatus nvarchar(10))
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lDate nvarchar(20)
	
	
if isnull(@rStatus,'') = ''
BEGIN
	Set @ldate = @rAttendanceDate	
	if ISDATE(@ldate)=1
	BEGIN
		if(@rAdmissionDate > @rAttendanceDate)
		BEGIN
			SET @rStatus = 'NA'
			RETURN @rStatus
		END
		if(@rLeftDate <= @rAttendanceDate)
		BEGIN
			SET @rStatus='L'
			RETURN @rStatus
		END
		 
	 END	
	END	    
	RETURN @rStatus
END
GO
PRINT N'Altering [sHrm].[fWeekHOffHolidayLeaveGet]...';


GO
 
 
ALTER FUNCTION [sHrm].[fWeekHOffHolidayLeaveGet](@rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rEmployeeId bigint,@rStatus nvarchar(20),@rOrgId smallint)
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN
 
	DECLARE @lDate nvarchar(20) = CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + CONVERT(nvarchar(10), @rDay)
	
	
 
	if(ISDATE(@lDate)=1)
	BEGIN
     IF  EXISTS(SELECT 1
		 from  sHrm.tLeave where  ReportDate = @lDate AND  OrgId = @rOrgid AND EmployeeId = @rEmployeeId AND BatchId =@rBatchid) 
		 BEGIN
				SET @rStatus = (Select LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId!=551 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
				RETURN @rStatus	
		END	 
	 END
	RETURN @rStatus	
	
END
GO
PRINT N'Creating [sAttendance].[fPresentAbsentGet]...';


GO

CREATE FUNCTION [sAttendance].[fPresentAbsentGet](@rRollNo int)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN
	Declare @lIsPresent bit
  Select 
		@lIsPresent=ISpresent from 	sAttendance.tStudentRegister SA 
		INNER JOIN sStudent.tAcademic A ON SA.Academicid=A.Id
		Where A.RollNo=@rRollNo
    RETURN ISNULL(@lIsPresent,0) 
END
GO
PRINT N'Altering [sAccounting].[vLedgerMaster]...';


GO


ALTER VIEW [sAccounting].[vLedgerMaster]

AS
	select	L.Id,
		L.Title,
		L.LedgerGroupId,
		L.LedgerTypeId,
		L.AccountingYearId,		 
		AY.AccountId,
		LedgerMainGroupId,
		LGM.Code
		
	FROM sAccounting.tLedgerMaster L 
		 INNER JOIN  sAccounting.tAccountingYearMaster AY 
	ON   L.AccountingYearId = AY.Id AND IsObsolete = 0
	 INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LedgerGroupId = LGM.Id  
	 AND L.AccountingYearId = LGM.AccountingYearId 
	 WHERE L.IsObsolete = 0
GO
PRINT N'Altering [sStudent].[vStudentCustomSearch]...';


GO

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

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


GO
ALTER PROCEDURE [sAcademic].[pClassGet]

	 @rId bigint,
	 @rEmployeeId bigint,
	 @rSubjectId int,
	 @rClassId int,
	 @rDivisionid int,
	 @rOrgId int,
	 @rClassworkDate Date	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			
			TSD.SubjectId ,
		    ISNULL( SM.Title,'') AS SubjectName,
			AC.Id,
			AC.Classwork,
		    AC.Homework,
		    AC.HomeWorkEndDate,
		    DM.Id AS DivisionId,
		    DM.ClassId,
		    ISNULL(CM.Title,'')as ClassName,
		    ISNULL(DM.Title,'')as DivisionName,
			DM.OrderIndex,
			REPLACE(CONVERT(VARCHAR(20), GETDATE(), 103),'/','') +'_'+ CONVERT(nvarchar(10),DM.Id) +'_'+CONVERT(nvarchar(10),TSD.SubjectId) AS UniqueId
	FROM 
	
			sAcademic.tTeacherSubjectDivision TSD			
			INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId = SM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON TSD.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM On CM.Id = DM.ClassId
			INNER JOIN sHrm.tEmployeeMaster EM On  TSD.EmployeeId = EM.Id
			LEFT JOIN sAcademic.tClasswork AC ON TSD.SubjectId = AC.SubjectId  
			AND  TSD.DivisionId = AC.DivisionId AND TSD.EmployeeId = AC.EmployeeId 
			AND AC.ClassWorkDate = @rClassworkDate
			AND ((AC.Id=@rId OR @rId=0))
	
			--[sSetup].[tClassSubject] CS 
			--Left JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
			--Left Join sAcademic.tClasswork AC ON AC.SubjectId=CS.SubjectId And AC.Id=@rId
			--LEFT JOIN sSetup.tClassMaster CM On CM.Id = CS.ClassId
			--LEFT JOIN sSetup.tDivisionMaster DM On DM.ClassId = CM.Id
			
	WHERE 
		(DM.OrgId=@rOrgId)		
		AND ((TSD.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((TSD.DivisionId=@rDivisionId) OR(@rDivisionId=0))
		AND ((TSD.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
		Order By DM.OrderIndex
END
GO
PRINT N'Altering [sAcademic].[pClassworkGet]...';


GO
 
ALTER PROCEDURE [sAcademic].[pClassworkGet]

	 @rId bigint,	 
	 @rSubjectId int,
	 @rClassId int,
	 @rEmployeeId bigint,
	 @rDivisionid int,
	 @rFromDate datetime,
     @rToDate datetime,
     @rOrgId int,
     @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	
	SELECT 
			 AC.Id,
			 AC.EmployeeId,
			 AC.ClassId,
			 AC.DivisionId,
			 AC.SubjectId,
			AC.ClassWorkDate,
		    AC.Classwork,
		    AC.Homework,
		    --AC.HomeWorkEndDate,
		    ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
		    AC.CreatedDateTime,
		    AC.BatchId,
   
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    BM.OrgId,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId
	FROM 
			--sAcademic.tTeacherSubjectDivision TSD		
			sAcademic.tClasswork AC
			INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId = SM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON AC.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM On AC.ClassId = CM.Id
			INNER JOIN sHrm.tEmployeeMaster EM On  AC.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On Bm.Id= AC.BatchId
			
	WHERE 
	      BM.OrgGroupBatchId = @rBatchId AND
		  ((AC.Id = @rId) OR (@rId = 0))
		AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
		AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
		AND	((DM.OrgId = @rOrgId) OR (@rOrgId = 0))
		AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
		AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
		order by AC.HomeWorkEndDate DESC
END
GO
PRINT N'Altering [sAcademic].[pTeacherSubjectAdd]...';


GO

ALTER PROCEDURE [sAcademic].[pTeacherSubjectAdd]
	
	@rTeacherSubjectImpXml [nvarchar](max),
	@rEmployeeId bigint,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rTeacherSubjectImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	  
	 DELETE TS FROM sAcademic.tTeacherSubject TS 
	 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TS.SubjectId
	 WHERE TS.EmployeeId=@rEmployeeId AND SM.OrgId = @rOrgId
	
	 INSERT INTO sAcademic.tTeacherSubject
		(
			EmployeeId,
			SubjectId
			)
		SELECT
			EmployeeId,
			SubjectId
		FROM OPENXML (@loDoc, '/Table/TeacherSubject', 1)
		WITH ( 
				EmployeeId bigint,
				SubjectId int
			  ) 
			  
		DELETE FROM sAcademic.tTeacherSubjectDivision WHERE 
		SubjectId NOT IN (
		SELECT SubjectId FROM sAcademic.tTeacherSubject TS
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TS.SubjectId
		WHERE EmployeeId=@rEmployeeId AND SM.OrgId = @rOrgId
		) AND EmployeeId=@rEmployeeId	  
		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAlert].[pAbsentStudentGet]...';


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

--SET @rToDate = dateadd(d,1,@rToDate)
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			CASE WHEN @rIsPresent=0 THEN
			replace (replace (
			replace(replace(replace(replace(replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[AbsentDates]',SR.AttendanceDate),
			'[AbsentReason]',ISNULL(AR.Title,'')),
			'[SubjectName]',ISNULL(SM.TItle,'')),
			'[LectureNo]',ISNULL(SR.PeriodNo,''))
			ELSE
			replace (
			replace(replace(replace(replace(replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[PresentDates]',SR.AttendanceDate),
			'[SubjectName]',ISNULL(SM.TItle,'')),
			'[LectureNo]',ISNULL(SR.PeriodNo,''))
			END
			 AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId
			
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sSetup.tSubjectMaster SM on SM.Id=SR.SubjectId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id
	 	
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SR.IsPresent = @rIsPresent)
		AND ((SR.PeriodNo=@rPeriodNo) OR (@rPeriodNo=0))
		AND (ISNULL(SC.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR ISNULL(@rDivisionIds,'')='')
   ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.Rollno
END
GO
PRINT N'Altering [sAssessment].[pExamDetailAdd]...';


GO

ALTER PROCEDURE [sAssessment].[pExamDetailAdd]
	 
	        @rId int
           ,@rExamId int
		   ,@rClassSubjectId int
		   ,@rMinimum decimal(10,2)
		   ,@rMaximum Decimal(10,2)
		   ,@rIsIncludeInTotal bit
		   ,@rIsDisplayInMarkSheet bit
		   ,@rIsShowSubjectGrade bit
		   ,@rDisplayOrder tinyint
		   ,@rGradeSetDetailId int
		   ,@rExamDate date
		   ,@rExamTime nvarchar(50)
		   ,@rExamTopic nvarchar(100)
		   ,@rCreatedUserId bigint
		   ,@rOrgId int
		   ,@rIsObsolete bit,
		   @rIsShowSubjectMark bit=1
		 
		   
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	
	 DECLARE @lNextNumber BIGINT 

IF NOT EXISTS(SELECT 1 FROM sAssessment.tExamMaster E INNER JOIN sSetup.tClassSubject CS ON E.ClassId = CS.ClassId 
WHERE E.Id = @rExamId AND CS.Id = @rClassSubjectId)
BEGIN
SELECT -111 AS Result -- Other Class Subject Selected
END 
--IF(@rId = 0)
 BEGIN TRANSACTION		
IF NOT EXISTS (SELECT 1 FROM [sAssessment].[tExamDetail] WHERE ExamId = @rExamId
				AND ClassSubjectId = @rClassSubjectId )
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tExamDetail]
			   (
			    [Id]
			   ,ExamId 
			   ,ClassSubjectId 
			   ,Minimum 
			   ,Maximum 
			   ,IsIncludeInTotal 
			   ,IsDisplayInMarkSheet 
			   ,IsShowSubjectGrade 
			   ,DisplayOrder 
			   ,GradeSetId 
			   ,ExamDate 
			   ,ExamTime 
			   ,ExamTopic 
			   ,UpdatedUserId
			   ,UpdatedDateTime,
			   IsShowSubjectMark
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rExamId 
			   ,@rClassSubjectId 
			   ,@rMinimum 
			   ,@rMaximum 
			   ,@rIsIncludeInTotal 
			   ,@rIsDisplayInMarkSheet 
			   ,@rIsShowSubjectGrade 
			   ,@rDisplayOrder 
			   ,@rGradeSetDetailId 
			   ,@rExamDate 
			   ,@rExamTime 
			   ,@rExamTopic 
			   ,0
			   ,sCommon.fGetDate(),
			   @rIsShowSubjectMark 
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
    BEGIN


IF @rIsObsolete = 1 
	  
	BEGIN
	IF EXISTS (SELECT R.Id FROM sAssessment.tResultDetail R INNER JOIN  [sAssessment].[tExamDetail] ED ON R.ExamDetailId = ED.Id and R.ExamDetailId=@rId AND R.Obtain > @rMaximum) 
    BEGIN
		SELECT -104 AS Result
		RETURN
    END
			
			 SET @lNextNumber = @rId
				UPDATE  [sAssessment].[tExamDetail]
				SET
						ExamId =@rExamId 
					   ,ClassSubjectId =@rClassSubjectId 
					   ,Minimum=@rMinimum 
					   ,Maximum=@rMaximum 
					   ,IsIncludeInTotal =@rIsIncludeInTotal 
					   ,IsDisplayInMarkSheet =@rIsDisplayInMarkSheet 
					   ,IsShowSubjectGrade =@rIsShowSubjectGrade 
					   ,DisplayOrder =@rDisplayOrder 
					   ,GradeSetId =@rGradeSetDetailId 
					   ,ExamDate =@rExamDate 
					   ,ExamTime=@rExamTime 
					   ,ExamTopic =@rExamTopic 
					   ,UpdatedUserId=@rCreatedUserId
					   ,UpdatedDateTime=sCommon.fGetDate(),
					   IsShowSubjectMark=@rIsShowSubjectMark 
				  WHERE Id = @rId 	   
				  SELECT @lNextNumber AS Result
			
				--COMMIT TRANSACTION
			 END 
	ELSE
		BEGIN
		
			IF EXISTS (SELECT R.Id FROM sAssessment.tResultDetail R INNER JOIN  [sAssessment].[tExamDetail] ED ON R.ExamDetailId = ED.Id and R.ExamDetailId=@rId) 
			AND @rIsObsolete = 0
			BEGIN
				SELECT -105 AS Result
				RETURN
			END
		
			DELETE FROM [sAssessment].[tExamDetail] WHERE ID = @rId
			SELECT @rId AS Result
		END		  
	END 

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


GO
ALTER PROCEDURE [sAssessment].[pMarkEntryRankUpdate]
	 @rExamId int,
	 @rDivisionId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
 		

--    ,ROW_NUMBER() OVER (ORDER BY TotalObtain) AS "Row Number"    -- Row number
--    ,RANK() OVER (ORDER BY TotalObtain) AS Rank                  -- skip next number
--    ,DENSE_RANK() OVER (ORDER BY TotalObtain) AS "Dense Rank"    -- continue next number 
--    ,NTILE(4) OVER (ORDER BY TotalObtain) AS Quartile            -- make number of rank group    


Update R Set R.RankNumber = 0 From sAssessment.tResult R 
Inner Join sStudent.tAcademic A ON A.Id = R.AcademicId  
 AND R.ExamId=@rExamId
 AND A.DivisionId = @rDivisionId 
 AND A.BatchId = @rBatchId

 

Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
INNER JOIN
(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
--(Select ROW_NUMBER() OVER(ORDER BY TotalObtain Desc, RS.AcademicId Asc) AS RankNumber,
--(Select RANK() OVER(ORDER BY TotalObtain Desc, RS.AcademicId Asc) AS RankNumber,
AcademicId 
from sAssessment.tResult RS
INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
AND ResultStatus='PASS'  ) A
ON A.AcademicId = R.AcademicId 
WHERE R.ExamId = @rExamId

 
SELECT 1 AS Result
 
END
GO
PRINT N'Altering [sAssessment].[pRptProgressCardGet]...';


GO

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

BEGIN 

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



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

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

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

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



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



DROP TABLE #tempProgressCard

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


GO
 


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

BEGIN 

DECLARE @GradeString nvarchar(1000),
@GradeSetId int
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  
	SELECT 
			ESGM.Title AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
			A.RollNo,
			CCEEM.AcademicId,
			--RD.Obtain,
			ISNULL(R.ResultStatus,'') AS ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(R.TotalMarks,0) AS TotalMarks,
			ISNULL(R.TotalObtain,0) AS TotalObtain,
			ISNULL(R.Percentage,0) AS Percentage,
			ISNULL(R.RankNumber,0) AS RankNumber,
			ISNULL(R.ResultGrade,0) AS ResultGrade,
			ISNULL(R.Percentile,0) AS Percentile,
			--SM.Title AS ClassSubject,
			--RD.Id AS ResultDetailId,
			ISNULL(R.Id,0) AS ResultId,
			--CS.Id AS SubjectId,
			--ED.Maximum,
			--RD.SubjectGrade,
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			--SM.Code AS SubjectCode,
			--SM.OrderIndex AS SubjectOrderIndex,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsMarksInDecimal,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			ISNULL(R.ResultRemark,'') AS ResultRemark,
			SO.DateOfBirth,
			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,
			SI.StudentPhoto,
			@GradeString AS GradeString,
			CCEEM.Grade,
			CCEEM.GradeIndicator,
			CCEEM.DescriptiveIndicator,
			CCEM.Title AS CoSubject,
			CCEM.OrderIndex AS CoOrderIndex,
			CCEGM.Title AS CoSubjectGroup,
			CCEGM.OrderIndex AS CoOrderIndexGroup,
			EM.IsDisplayPrincipalSign,
			Em.IsDisplayTeacherSign,
			EI.EmployeeSign ,
			SR.StudentHeight,
			SR.TotalDays,
			SR.PresentDays,
			SR.StudentWeight,
			EM.IsCoScholasticGrade,
			EM.IsCoScholasticGradeIndicator,
			EM.IsCoScholasticGradeDesIndicator,
				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,
		SR.ResultRemark3,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		SR.ResultRemark1,
		SR.ResultRemark2,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,

		sAssessment.fGetGradepoint(CCEEM.Grade) AS GradePoint,
		SF.FatherName,
		SF.MotherName,
		EM.IsDisplayParentName
	FROM 
			 
			 
			sAssessment.tCCECSExamScore CCEEM INNER JOIN   
			--INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			  sAssessment.tExamMaster EM ON EM.Id=CCEEM.ExamId AND CCEEM.ExamId=@rExamId
			--INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId		
			INNER JOIN sStudent.tAcademic A ON A.Id=CCEEM.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sAssessment.tCCECSMaster CCEM ON CCEM.Id=CCEEM.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CCEGM ON CCEGM.Id= CCEM.CCECAGroupId	
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			
			LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			LEFT JOIN sAssessment.tResult R ON R.AcademicId = CCEEM.AcademicId AND R.ExamId = CCEEM.ExamId
			LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	WHERE 
			
		EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		--AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))		
		AND (CCEEM.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))		
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		order by A.RollNo--,CS.OrderIndex 
		--AND A.id = 1005000000007
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]...';


GO
 
 


ALTER PROCEDURE [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClass 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,
	 @rOrgId int=0
	  
	 
	   
	 
	 
	  
	 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

  
-- --drop table sAssessment.tTempAllExam	

 --Select * from   sAssessment.tTempAllExamSubjectActivity
DECLARE @GradeString nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		
		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),
		--ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(150),
		Remark2 nvarchar(150),
		Remark3 nvarchar(150),
		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), 
		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),
		
		SubActivityGrade1 nvarchar(10),
		ActivityGrade1 nvarchar(10),
		
		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),
		
		SubActivityGrade2 nvarchar(10),
		ActivityGrade2 nvarchar(10),
		
		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),
		
		SubActivityGrade3 nvarchar(10),
		ActivityGrade3 nvarchar(10),
		
		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),
		
		SubActivityGrade4 nvarchar(10),
		ActivityGrade4 nvarchar(10),
		
		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),
		
		SubActivityGrade5 nvarchar(10),
		ActivityGrade5 nvarchar(10),
		
		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),
		
		SubActivityGrade6 nvarchar(10),
		ActivityGrade6 nvarchar(10),
		
		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),
		
		--SubActivityGrade7 nvarchar(10),
		
		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),
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		TotalDays smallint,
		PresentDays smallint,
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		IsDisplayParentName bit,
		FatherName nvarchar(30),
		MotherName nvarchar(30),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		
		ActivityName nvarchar(200),
		SubActivityName nvarchar(200),
		SubActivityId int,
		ActivityId Int,
		 SubActivityGrade nvarchar(10),
		 ActivityGrade nvarchar(10),
		SubActivityGradeIndicator nvarchar(50),
		SubActivityDescriptiveIndicator nvarchar(200),
		SubjectActivityOrderIndex Smallint,
		SubActivityOrderIndex smallint,
		ColumnSubjectCount SmallInt,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		Height1 decimal(6,2),
		Height2 decimal(6,2),
		Height3 decimal(6,2),
		Height4 decimal(6,2),
		Height5 decimal(6,2),
		Height6 decimal(6,2),
		Weight1 decimal(6,2),
		Weight2 decimal(6,2),
		Weight3 decimal(6,2),
		Weight4 decimal(6,2),
		Weight5 decimal(6,2),
		Weight6 decimal(6,2),
		TotalDays1 smallint,
		PresentDays1 smallint,
		TotalDays2 smallint,
		PresentDays2 Smallint,
		TotalDays3 smallint,
		PresentDays3 smallint,
		TotalDays4 smallint,
		PresentDays4 smallint,
		TotalDays5 smallint,
		PresentDays5 smallint,
		TotalDays6 smallint,
		PresentDays6 smallint,
		MyActivity1 nvarchar(200),
		MyActivity2 nvarchar(200),
		MyActivity3 nvarchar(200),
		MyActivity4 nvarchar(200),
		MyActivity5 nvarchar(200),
		MyActivity6 nvarchar(200),
		GeneralRemark1 nvarchar(200),
		GeneralRemark2 nvarchar(200),
		GeneralRemark3 nvarchar(200),
		GeneralRemark4 nvarchar(200),
		GeneralRemark5 nvarchar(200),
		GeneralRemark6 nvarchar(200),
		PresentAddress nvarchar(500) ,
		 MobileNo nvarchar(50),
		House nvarchar(20),
		 
		AttendanceTerm1 int ,
		AttendanceTerm2 int,
		WorkingDaysTerm1 int,
		WorkingDaysTerm2 int,
		  BloodGroup nvarchar(10),
		  GradeSetIdText nvarchar(50),
		  IsDisplayMonthlyAttendanceText nvarchar(20),
		  DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100)
	)	
	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	
	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,
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	SubActivityGrade,
	ActivityGrade,
	ActivityName,
	SubActivityName,
	SubActivityId,
	ActivityId,
	SubActivityGradeIndicator,
	SubActivityDescriptiveIndicator,
	SubjectActivityOrderIndex,
	SubActivityOrderIndex,
	ColumnSubjectCount,
	MarksheetHeaderA4,
	IsImageHeader,
	PresentAddress,
 	MobileNo,
	House,
	AttendanceTerm1   ,
	AttendanceTerm2  ,
	WorkingDaysTerm1  ,
	WorkingDaysTerm2  ,
	BloodGroup,
	GradeSetIdText,
	IsDisplayMonthlyAttendanceText,
	DentalHygiene,
	VisionLeft,
	VisionRight,
	TeacherSignCaption,
	PrincipalSignCaption,ParentSignCaption
	)
	
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
		A.RollNo,
		R.ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.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,
		SI.StudentPhoto,
		@GradeString AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    SAM.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.TotalDays,
		SR.PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		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,
		EI.EmployeeSign,
		SSA.Grade AS SubActivityGrade,
		ISNULL(SAS.Grade,'') AS ActivityGrade,
		SAM.Title AS ActivityName,
		SSAM.Title AS SubActivityName,
		SSA.SubjectSubActivityId AS SubActivityId,
		SAM.Id AS ActivityId,
		SSA.GradeIndicator AS SubActivityGradeIndicator,
		SSA.DescriptiveIndicator AS SubActivityDescriptiveIndicator,
		SAM.OrderIndex AS SubjectActivityOrderIndex,
		SSAM.OrderIndex AS SubActivityOrderIndex,
		CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
				ELSE 1 END   AS   ColumnSubjectCount,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader	,
		ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		 SC.ParentContactNo,
		ISNULL(HM.Title,'') AS House,
		ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
		ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
		ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
		ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
		ISNULL(BGM.Title,'') AS BloodGroup,
		CONVERT (nvarchar(50),EM.GradeSetId) AS GradeSetIdText,
				Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
				ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		ISNULL(TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(ParentSignCaption,'') AS ParentSignCaption
			 
			
FROM 


	
			 
	sAssessment.tCCESubjectSubActivityExamScore SSA
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
	INNER JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
	LEFT JOIN sAssessment.tCCESubjectActivityExamScore SAS ON SAS.SubjectActivityId= SAM.Id
	 INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	
	 INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
	INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = SAM.ClassSubjectId
			
			
	--INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
	  

	 
	 INNER JOIN sStudent.tAcademic  A ON   SSA.AcademicId = A.Id
	 
	LEFT JOIN    sAssessment.tCCEResult CCER    ON  CCER.AcademicId=A.Id
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	 
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	
	 LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = A.Id AND OS.ClassSubjectId = ED.ClassSubjectId  
	
	LEFT JOIN sAssessment.tResult R ON R.AcademicId = SSA.AcademicId AND R.ExamId = SSA.ExamId
	LEFT JOIN sAssessment.tResultDetail RD  ON R.Id = RD.ResultId AND ED.ExamId = R.ExamId
	LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = StuM.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =Stum.ID
	LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		SSA.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClass) OR (@rClass=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) ) 
		 
	 
	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
	 
	--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	
	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
					
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,					
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
					 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
					 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
					 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark 
					 									
					 From
						 
						 sAssessment.tResult R 
						INNER JOIN  sAssessment.tResultDetail RD ON RD.ResultId = R.Id						
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster 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)  
						
	
	 execute(@query)
 
	 set @query ='update T SET
					
					 
					 SubActivityGrade' + convert(nvarchar(15),@lCount)+ '=SSA.Grade	
					 						
					 From
						sAssessment.tCCESubjectSubActivityExamScore SSA				
						inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	 					
						WHERE SSA.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
 
  set @query ='update T SET
					
					  ActivityGrade' + convert(nvarchar(15),@lCount)+ '=SAS.Grade	
					 						
					 From
						sAssessment.tCCESubjectActivityExamScore SAS				
						inner JOIN 	#TempAllExam  T ON T.ActivityId = SAS.SubjectActivityId And T.AcademicId = SAS.AcademicId	 					
						WHERE SAS.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
	-- set @query ='update T SET
					
	--				 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
	--				 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
	--				 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
	--				 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
	--				 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
	--				 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark
	--				 From
	--					sAssessment.tCCESubjectSubActivityExamScore SSA
						
	--					inner JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
	--					inner JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
	--					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
	--					inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.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.Title,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	execute(@query)*/
		
		
	set @lCount = @lCount -1
	end


	
	
	
	

	
	SELECT @rBuilder1 , T.*
	FROM #TempAllExam T
	
	
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	
	END

--end
/*
 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
					
					--sAssessment.tCCESubjectActivityMaster SAM 	
	--		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.SubjectActivityId=SAM.Id  
	--		INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	--		INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
	--		 INNER JOIN sStudent.vStudentAcademic  A ON   A.ClassId = CS.ClassId AND  A.StatusId = 1
	--		 LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SSA ON SSA.AcademicId = A.AcademicId AND SSA.SubjectSubActivityId= SSAM.Id  	
			  */
GO
PRINT N'Altering [sAssessment].[pRptSubjectActivityExamDetailGet]...';


GO
 

ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailGet]
	  
	   @rOrgId int=0
	  ,@rExamId int=0,
	  @rClass int=0,
	  @rDivisionId int=0,
	  @rBatchId int=0,
	  @rBuilder1 nvarchar(max)='',
	  @rAcademicId bigint=0,
	  @rCode nvarchar(20)='',
	  @rFromRollNo int=0,
	  @rToRollNo int=0
	  
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 
Declare @GradeString nvarchar(500),@GradeSetId int
SELECT @GradeSetId = GradesetId  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

	SELECT 			 
				 Convert(nvarchar(20),SA.AcademicId) AS   AcademicIdText,	
				CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
			   AIS.Grade,
				 SAM.Title AS SubjectActivityTitle,
				 SSA.Title AS SubjectSubActivityTitle,
				 SAM.Id AS ActivityId,
				 SSA.Id AS SubjectSubActivityId,
				 SAM.OrderIndex AS ActivityOrderIndex,
				 SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
				ISNULL(EM.Remark1,'') AS Remark1,
				ISNULL(EM.Remark2,'') AS Remark2,
				ISNULL(EM.Remark3,'') AS Remark3,
				EM.DisplayTitle,
				EM.IsRankNo, 
				EM.IsGrade, 
				EM.IsPercentile,
				EM.IsPercentage,
				EM.IsSubjectPercentile,
				EM.IsProcessResult,
				EM.IsNegativeMarks,
				EM.IsIncludeCoScholastic,
				EM.IsOnPrePrinted,
				EM.IsDisplayPhoto,
				EM.IsDisplayBirthDate,
				EM.IsLockForEdit,
				EM.IsDisplaySchoolName,			
				EM.IsDisplayAttendance,
				EM.IsDisplayHeightWeight,
				EM.IsResultStatus,
				REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
				REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
				EM.FooterAdjustment,
				EM.DetailAdjustment,
				EM.IsDisplayGradeString,
				EM.IsDisplayParentName,
				SA.FirstName + ' ' +SA.MiddleName +' ' +SA.LastName AS Name,
				SO.DateOfBirth,
				CMM.Title AS ClassName,
				SA.code,
				SR.PresentDays,			
				SR.TotalDays,
				SR.StudentHeight,
				SR.StudentWeight,
				SF.FatherName,
				SF.MotherName,
				SAM.ClassSubjectId ,
				SM.Title AS SubjectName,
				SM.OrderIndex AS SubjectOrderIndex,
				CMM.DisplayTitle AS Class,
				DM.DisplayTitle AS Division,
				SR.ResultRemark1,
				SR.ResultRemark2,						 
				SI.StudentPhoto , 
				ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
				 CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
				ELSE 1 END   AS   ColumnSubjectCount,
				CS.OrderIndex,
				EM.SubjectGroupPerPage,
				AIS.GradeIndicator,
				EM.IsCoScholasticGradeIndicator,
				EI.EmployeeSign,
				Em.IsDisplayPrincipalSign,
				EM.IsDisplayTeacherSign,
				EM.IsCoScholasticGradeDesIndicator,
				EM.IsCoScholasticGrade,
					Em.IsDisplayParentName,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			HM.Title AS House,
			BM.Title AS BAtch  ,
			 [sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			 ED.IsShowSubjectGrade,
			 @GradeString AS GradeString,
			 Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			 TeacherSignCaption,
			 PrincipalSignCaption,
			 ParentSignCaption
			FROM 
			 sAssessment.tCCESubjectActivityMaster SAM 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
			INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			INNER JOIN sStudent.vStudentAcademic SA ON  SA.ClassId = CS.ClassId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId			 
			LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id  	
			LEFT JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			LEFT JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId	AND ED.ClassSubjectId = CS.ClassSubjectId 		   
		    LEFT  JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		    LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		    LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
		    INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
		    INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId
		    LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	        LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
	        LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
		    LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
		    LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.AcademicId AND EM.ID=RD.ExamId AND CS.ClassSubjectId=RD.ClassSubjectID    
			 WHERE
				 ((SA.AcademicId=@rAcademicId) OR(@rAcademicId=0))
				AND 
				((CS.ClassId=@rClass) OR (@rClass=0))
				And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
				And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
				and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				And AIS.ExamId=@rExamId
				AND((STum.Code = @rCode) OR(@rCode=''))
				AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
				AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
				AND  SA.StatusId = 1
				 ORDER BY SA.RollNo 
	 
END
GO
PRINT N'Altering [sAttendance].[pAttenanceRegisterGet]...';


GO

ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0,
	 @rStatus int=0 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

--Select * from sAttendance.tTempAttendance

DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	
	
DECLARE @lOrgId  int
--DECLARE @lSchoolRemark1  nvarchar(500)
--DECLARE @lSchoolRemark2  nvarchar(500)
--DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

SELECT  @lOrgId=RG.OrgId,
--@lSchoolRemark1 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark1,'')  ELSE RG.SchoolRemark1 END,
--@lSchoolRemark2= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark2,'')  ELSE RG.SchoolRemark2 END,
--@lSchoolRemark3 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark3,'')  ELSE RG.SchoolRemark3 END,
@lSchoolRequiredSignature= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRequiredSignature,'')  ELSE RG.SchoolRequiredSignature END 
 
FROM sCommon.tReportRemarkGroupMaster RGM LEFT JOIN sCommon.tReportRemarkGroupOrg RG ON RGM.Id = RG.ReportRemarkGroupId AND RG.OrgId = @rOrgId AND RG.ReportRemarkGroupId=1 where RGM.Id=1
 
-- select @lSchoolRequiredSignature as sig
 	
BEGIN 
	 CREATE Table #AttendanceRegistertempTable
(
	TID int identity(1,1),
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(50),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(50),
	DivisionName nvarchar(50),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	EmployeeName nvarchar(100),
	DateOfBirth date,
	Religion nvarchar(50),
	MotherName nvarchar(50),
	FamilyCast nvarchar(100)
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId,
	EmployeeName,
	DateOfBirth,
	Religion,
	MotherName,
	FamilyCast
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	@lSchoolRequiredSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 EM.FirstName+' ' + EM.LastName AS EmployeeName,
	 SO.DateOfBirth,
	 RE.Title As Religion,
	 Sf.MotherName,
	 SO.FamilyCast
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN  sStudent.tStudentFamily SF ON Sf.StudentId=Sa.StudentID
            INNER JOIN sCommon.tReligionMaster RE On RE.Id=SO.ReligionId
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	           AND ((SA.StatusId=@rStatus)OR (@rStatus=0))

				
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=31
BEGIN
INSERT INTO #TempDaysTempTable
(
	DayPart ,
   Value
)

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,@li,@rBatchId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

 

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			ISNULL(ABU.AUCount,0) AS AbsentUpto,
			ISNULL(TC.TCount,0) AS AttendanceCount,
		    ISNULL(AC.ACount,0) As  AbsentCount,
		    ISNULL(PC.PCount,0) As  PresentUpto,	    
		    
		    ClassOrderIndex,
		    DivisionOrderIndex,
		    FooterSignature,
			(ISNULL(TotalPresent,0) + ISNULL(TC.TCount,0)) AS TotalPresent,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,1 ,@rBatchId ,@rDivisionId , isnull([1],''),@rOrgId )  AS P1,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,2 ,@rBatchId ,@rDivisionId , isnull([2],''),@rOrgId )  AS P2,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,3 ,@rBatchId ,@rDivisionId , isnull([3],''),@rOrgId )  AS P3,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,4 ,@rBatchId ,@rDivisionId , isnull([4],''),@rOrgId )  AS P4,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,5 ,@rBatchId ,@rDivisionId , isnull([5],''),@rOrgId )  AS P5,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,6 ,@rBatchId ,@rDivisionId , isnull([6],''),@rOrgId ) AS P6,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,7 ,@rBatchId ,@rDivisionId , isnull([7],''),@rOrgId ) AS P7,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,8 ,@rBatchId ,@rDivisionId , isnull([8],''),@rOrgId ) AS P8,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,9 ,@rBatchId ,@rDivisionId , isnull([9],''),@rOrgId ) AS P9,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,10 ,@rBatchId ,@rDivisionId , isnull([10],''),@rOrgId ) AS P10,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,11 ,@rBatchId ,@rDivisionId , isnull([11],''),@rOrgId ) AS P11,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,12 ,@rBatchId ,@rDivisionId , isnull([12],''),@rOrgId ) AS P12,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,13 ,@rBatchId ,@rDivisionId , isnull([13],''),@rOrgId ) AS P13,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,14 ,@rBatchId ,@rDivisionId , isnull([14],''),@rOrgId ) AS P14,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,15 ,@rBatchId ,@rDivisionId , isnull([15],''),@rOrgId ) AS P15,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,16 ,@rBatchId ,@rDivisionId , isnull([16],''),@rOrgId ) AS P16,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,17 ,@rBatchId ,@rDivisionId , isnull([17],''),@rOrgId ) AS P17,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,18 ,@rBatchId ,@rDivisionId , isnull([18],''),@rOrgId ) AS P18,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,19 ,@rBatchId ,@rDivisionId , isnull([19],''),@rOrgId ) AS P19,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,20 ,@rBatchId ,@rDivisionId , isnull([20],''),@rOrgId ) AS P20,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,21 ,@rBatchId ,@rDivisionId , isnull([21],''),@rOrgId ) AS P21,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,22 ,@rBatchId ,@rDivisionId , isnull([22],''),@rOrgId ) AS P22,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,23 ,@rBatchId ,@rDivisionId , isnull([23],''),@rOrgId ) AS P23,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,24 ,@rBatchId ,@rDivisionId , isnull([24],''),@rOrgId ) AS P24,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,25 ,@rBatchId ,@rDivisionId , isnull([25],''),@rOrgId ) AS P25,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,26 ,@rBatchId ,@rDivisionId , isnull([26],''),@rOrgId ) AS P26,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,27 ,@rBatchId ,@rDivisionId , isnull([27],''),@rOrgId ) AS P27,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,28 ,@rBatchId ,@rDivisionId , isnull([28],''),@rOrgId ) AS P28,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,29 ,@rBatchId ,@rDivisionId , isnull([29],''),@rOrgId ) AS P29,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,30 ,@rBatchId ,@rDivisionId , isnull([30],''),@rOrgId ) AS P30,
			[sAttendance].[fWeekHOffHolidayGet](@rForYear ,@rForMonth ,31 ,@rBatchId ,@rDivisionId , isnull([31],''),@rOrgId ) AS P31,
			 
			
	 	--	 isnull([1],'') AS P1,
			--isnull([2],'') AS P2,
			--isnull([3],'') AS P3,
			--isnull([4],'') AS P4,
			--isnull([5],'') AS P5,
			--isnull([6],'') AS P6,
			--isnull([7],'') AS P7,
			--isnull([8],'') AS P8,
			--isnull([9],'') AS P9,
			--isnull([10],'') AS P10,
			--isnull([11],'') AS P11,
			--isnull([12],'') AS P12,
			--isnull([13],'') AS P13,
			--isnull([14],'') AS P14,
			--isnull([15],'') AS P15,
			--isnull([16],'') AS P16,
			--isnull([17],'') AS P17,
			--isnull([18],'') AS P18,
			--isnull([19],'') AS P19,
			--isnull([20],'') AS P20,
			--isnull([21],'') AS P21,
			--isnull([22],'') AS P22,
			--isnull([23],'') AS P23,
			--isnull([24],'') AS P24,
			--isnull([25],'') AS P25,
			--isnull([26],'') AS P26,
			--isnull([27],'') AS P27,
			--isnull([28],'') AS P28,
			--isnull([29],'') AS P29,
			--isnull([30],'') AS P30,
			--isnull([31],'') AS P31, 
			 EmployeeName ,
 
             sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth,
              DateOfBirth,Religion,MotherName,FamilyCast
--,
--AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LC' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'EL' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate
		,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,EmployeeName,
		DateOfBirth,Religion,MotherName,FamilyCast
      -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
            
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
		LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS AUCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 0	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) ABU ON ABU.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS TotalPresent  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
	        AND
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) AA ON AA.AcademicId = PivotTable.AcademicId
 
    ORDER BY RollNo;
 

select * from #TempDaysTempTable
 

drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	
	
END
GO
PRINT N'Altering [sAttendance].[pRptMonthlyAttendanceAverage]...';


GO

 
ALTER PROCEDURE [sAttendance].[pRptMonthlyAttendanceAverage]
	 
	  
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAttendanceTypeId tinyint=0,
	 @rSubjectId int=0,
	 
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int,
	 @rFromAverage decimal=0,
	 @rToAverage decimal=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 
			 MS.ForYear,
			 (select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1 AND SR.IsPresent =1 AND A.OrgId = @rOrgId AND SO.GenderId=1
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))) AS PresentBoys ,
			 
			 
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1 AND SR.IsPresent =0 AND A.OrgId = @rOrgId AND SO.GenderId=1
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))) AS Absentboys,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1 AND SR.IsPresent =0 AND A.OrgId = @rOrgId AND SO.GenderId=2
			AND ((A.DivisionId=@rDIvisionID) OR (@rDivisionId=0))) AS PresentGirls,
			
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
	        
		    AND Month(SR.AttendanceDate) = MS.ForMonth
		    AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND SR.AttendanceTypeId =1 AND SR.IsPresent =0 AND A.OrgId = @rOrgId AND SO.GenderId=2
			AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0))) AS AbsentGirls	,
			
			MS.WorkingDays,
			DateName(mm,Dateadd(mm,MS.ForMonth,-1)) AS Month_Title,ForMonth
			 
		 
			
	FROM 
	  sAttendance.tMonthlySetup MS  
	  INNER JOIN sSetup.tClassMaster CM On Cm.Id=MS.ClassId 
	  INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id
		WHERE 
			(MS.BatchId=@rBatchId)
			AND (MS.ClassId=@rClassId)
			AND ((Dm.Id=@rDivisionId) OR (@rDivisionId=0))
	Order by MS.ForYear,MS.ForMonth	
		--AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		--AND ((MR.ForYear=@rForYear) OR (@rForYear=0))
		--AND ((MR.ForMonth=@rForMonth) OR (@rForMonth=0))
		 
		--AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))	AND ((SV.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		--AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		--AND ((MR.AveragePresence >= @rFromAverage) OR (@rFromAverage=0))
		--AND ((MR.AveragePresence <= @rToAverage) OR (@rToAverage=0))
		 
END
GO
PRINT N'Altering [sAttendance].[pStudentRegisterBulkAdd]...';


GO
ALTER PROCEDURE [sAttendance].[pStudentRegisterBulkAdd]
	 
	@rDivisionId int,
	@rEmployeeId bigint,
	@rAttendanceTypeId tinyint,
	@rAttendanceDate date,
	@rSubjectId int,
	@rstrRollNo nvarchar(max),
	@rRepeatCount tinyint,
	@rIsPresent bit,
	--@rLeaveReasonId int,
	@rCreatedUserId bigint,
	@rOrgId smallint,
	@rBatchId int
	--@rIsDeleted bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lCount INT
	 DECLARE @rAcademicId bigint
	 DECLARE @lIsPresent bit
	
	
DELETE   sAttendance.tStudentRegister 
FROM sAttendance.tStudentRegister R
INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
WHERE  A.BatchId = @rBatchId
AND A.DivisionId = @rDivisionId
AND AttendanceTypeId=@rAttendanceTypeId 
AND AttendanceDate=@rAttendanceDate
	
--	DELETE FROM sAttendance.tStudentRegister R WHERE 
--			--AcademicId IN(Select AcademicId FROM sAttendance.tPresentTempRegister) 
--	AND AttendanceTypeId=@rAttendanceTypeId 
--AND AttendanceDate=@rAttendanceDate		


 create table #tableRollNo
 (
	RollNo int
 )
 Insert into #tableRollNo
(
	RollNo
)
SELECT 
DISTINCT cast(item as int) FROM  sCommon.fnsplit(@rstrRollNo,'.') 
 
		INSERT INTO sAttendance.tStudentRegister
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			--LeaveReasonId,
			CreatedUserId,
			CreatedDateTime
		)
		Select 
			SN.AcademicId,
			@rEmployeeId,
			@rAttendanceTypeId,
			@rAttendanceDate,
			@rSubjectId,
			@rRepeatCount,
			IsPresent = 
			CASE SN.Rollno WHEN  TR.RollNo
			THEN
				0
			Else
				1
				END,
			@rCreatedUserId,
			sCommon.fGetDate()
		from
			sStudent.vStudentName SN LEFT JOIN #tableRollNo TR ON SN.RollNo = TR.RollNo
		WHERE 
			SN.DivisionId=@rDivisionId
			AND SN.OrgId=@rOrgId
			AND SN.BatchId=@rBatchId
			AND SN.StatusId!=3
		 
 
	 	  SELECT 1 AS Result
 
	--	Select 
	--	SN.RollNo ,
	--		SN.AcademicId,
	--		@rEmployeeId,
	--		@rAttendanceTypeId,
	--		@rAttendanceDate,
	--		@rSubjectId,
	--		@rRepeatCount,
			 
	--		CASE SN.RollNo WHEN TR.RollNo
	--		THEN
	--			1
	--		Else
	--			0
	--			END AS IsPresent,
	--		@rCreatedUserId,
	--		sCommon.fGetDate()
	--	from
	--		sStudent.vStudentName SN LEFT JOIN #tableRollNo TR ON SN.RollNo = TR.RollNo
	--WHERE 
	--SN.DivisionId=@rDivisionId
	--AND SN.OrgId=@rOrgId
	--AND SN.BatchId=@rBatchId
	--	AND SN.StatusId!=3
	--SELECT 
	--	row_number() over(order by AcademicId) AS RowId, AcademicId,1 AS IsPresent into sAttendance.tPresentTempRegister 
	--FROM sStudent.vStudentName SN
	--WHERE 
	--		SN.DivisionId=@rDivisionId
	--	AND SN.OrgId=@rOrgId
	--	AND SN.BatchId=@rBatchId
	--	AND SN.StatusId!=3
	--	AND (SN.RollNo NOT IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rstrRollNo,'.'))OR (@rstrRollNo=''))
	
	
	
	--IF (@rstrRollNo<>'')
	--BEGIN
	--SELECT 
	--	row_number() over(order by AcademicId) AS RowId, AcademicId,0 AS IsPresent into sAttendance.tAbsentTempRegister 
	--FROM sStudent.vStudentName SN
	--WHERE 
	--		SN.DivisionId=@rDivisionId
	--	AND SN.OrgId=@rOrgId
	--	AND SN.BatchId=@rBatchId
	--	AND SN.StatusId!=3
	--	AND (SN.RollNo IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rstrRollNo,'.'))OR (@rstrRollNo=''))
		
	----DELETE FROM sAttendance.tStudentRegister WHERE 
	----		AcademicId IN(Select AcademicId FROM sAttendance.tAbsentTempRegister) 
	----	AND AttendanceTypeId=@rAttendanceTypeId 
	----	AND AttendanceDate=@rAttendanceDate
	--END
	
	--SELECT @lCount =  COUNT(AcademicId) FROM sAttendance.tPresentTempRegister 


	--WHILE @lCount > 0 
	--BEGIN
	
	--SELECT @rAcademicId=AcademicId,@lIsPresent=IsPresent FROM sAttendance.tPresentTempRegister WHERE RowId=@lCount
	
		--INSERT INTO sAttendance.tStudentRegister
		--(
		--	AcademicId,
		--	EmployeeId,
		--	AttendanceTypeId,
		--	AttendanceDate,
		--	SubjectId,
		--	RepeatCount,
		--	IsPresent,
		--	--LeaveReasonId,
		--	CreatedUserId,
		--	CreatedDateTime
		--)
		--VALUES
		--(
		--	@rAcademicId,
		--	@rEmployeeId,
		--	@rAttendanceTypeId,
		--	@rAttendanceDate,
		--	@rSubjectId,
		--	@rRepeatCount,
		--	@lIsPresent,
		--	--@rLeaveReasonId,
		--	@rCreatedUserId,
		--	sCommon.fGetDate()
		--)	
		
	 --	 SELECT @rAcademicId AS Result
	-- 	 SET @lCount = @lCount - 1	
	-- END
	--	DROP TABLE sAttendance.tPresentTempRegister 
		
	--IF (@rstrRollNo<>'')
	--BEGIN	
	--SELECT @lCount =  COUNT(AcademicId) FROM sAttendance.tAbsentTempRegister 

	--WHILE @lCount > 0 
	--BEGIN
	
	--SELECT @rAcademicId=AcademicId,@lIsPresent=IsPresent FROM sAttendance.tAbsentTempRegister WHERE RowId=@lCount
	
	--	INSERT INTO sAttendance.tStudentRegister
	--	(
	--		AcademicId,
	--		EmployeeId,
	--		AttendanceTypeId,
	--		AttendanceDate,
	--		SubjectId,
	--		RepeatCount,
	--		IsPresent,
	--		--LeaveReasonId,
	--		CreatedUserId,
	--		CreatedDateTime
	--	)
	--	VALUES
	--	(
	--		@rAcademicId,
	--		@rEmployeeId,
	--		@rAttendanceTypeId,
	--		@rAttendanceDate,
	--		@rSubjectId,
	--		@rRepeatCount,
	--		@lIsPresent,
	--		--@rLeaveReasonId,
	--		@rCreatedUserId,
	--		sCommon.fGetDate()
	--	)	
		
	-- 	 SELECT @rAcademicId AS Result
	-- 	 SET @lCount = @lCount - 1	
	-- END
	--	DROP TABLE sAttendance.tAbsentTempRegister 
	--END
	--	SELECT 1 AS Result
	 	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sBiometric].[pBiometricReportData]...';


GO
ALTER PROCEDURE [sBiometric].[pBiometricReportData]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgId int,
	 @rDeptId int,
	 @rForYear int=0,
	 @rForMonth int=0,
	 @rIsFirstIn bit=0,
	 @rIsLastOut bit=0,
	 @rIsOT bit=0,
	 @rIsLateBy	bit=0,
	 @rIsEarlyBy bit=0,
	 @rIsDuration  bit=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lATTN_DATE NVARCHAR(20)
	
	
	SET @lATTN_DATE = CONVERT(NVARCHAR(10),@rForYear) + '-' + Right('000000' + CONVERT(NVARCHAR, @rForMonth), 2) + '-01'
	
	SELECT 
	
	datediff(day, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE),
              dateadd(month, 1, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE))) AS DayCount,
 
	 @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
	T.*,
	E.Code,	
	E.ShortName,
	DM.Displaytitle DeptName,
	DM.Code AS DeptCode,
	E.OrgID,
	DM.Id AS DepartmentId,
	EDM.Title AS Designation,
	EDM.Code AS DesignationCode,
	 @rIsFirstIn AS IsFirstIn,
	 @rIsLastOut AS IsLastOut,
	 @rIsOT AS IsOT,
	 @rIsLateBy	AS IsLateBy,
	 @rIsEarlyBy AS IsEarlyBy,
	 @rIsDuration  AS IsDuration,
	 E.FirstName +' ' + E.MiddleName +' '+ E.LastName AS Name,
	 sBiometric.fEmployeeLeaveTypeGet(Attn_Dt,T.EmployeeId) AS LeaveStatus
	from 
		sBiometric.tMonthTrans T
		LEFT JOIN sHRM.tEmployeeMaster E on E.Id = T.EmployeeId
		LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = E.Id
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
		LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId
	WHERE 
		(E.OrgId=@rOrgId) AND
		(DM.Id = @rDeptId OR @rDeptId = 0)		 
		AND
		(T.Attn_dt = @lATTN_DATE)
    Order by E.Code,T.Attn_dt
END
GO
PRINT N'Altering [sBiometric].[pEmployeeCheckInAdd]...';


GO

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

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

 
END
GO
PRINT N'Altering [sBiometric].[pEmployeeCheckInGet]...';


GO
 

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


GO

ALTER PROCEDURE [sBiometric].[pRptEmployeeCheckInGet]
	 
	 @rOrgId int ,
	  @rBuilder1 nvarchar(max)='',
	  @rBuilder2 nvarchar(max)='',
	  @rdate date=''
	  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 Select 
			 
			B.EmployeePhoto ,
			EMp.FirstName+' ' +EMp.MiddleName+' '+emp.LastName AS Name,
			B.CheckInTime,
			Emp.Id As EmployeeID ,
			B.CheckOutTime,
			B.Id,
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2
	 from sHrm.tEmployeeMaster EMP  
	 INNER JOIN sBiometric.tEmployeeCheckIn B ON B.EmployeeID=EMP.Id
	 WHere EMp.OrgId=@rORgId  ANd @rDate=convert(date,B.CheckInTime)
	
END
GO
PRINT N'Altering [sBiometric].[pRptEmployeeWiseMonthlyAttendanceGet]...';


GO
 

ALTER PROCEDURE [sBiometric].[pRptEmployeeWiseMonthlyAttendanceGet]
	 
	 @rOrgId int ,
	  @rBuilder1 nvarchar(max)='',
	  @rBuilder2 nvarchar(max)='' ,
	  @rFromMonth int=0,
	  @rFromyear int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

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


GO
ALTER PROCEDURE [sBiometric].[pTimeSheetListGet]
	 @rEmployeeId bigint=0,
	 @rFromDate Date,
	 @rToDate Date,
	 @rStatus nvarchar(10) = '0'

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	CREATE TABLE #TempMonthTrans
	(
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20)
	)
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	SELECT TM.*,MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,
	Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave,EM.FirstName + ' ' + EM.LastName As ShortName,EM.Code as EmpCode , [sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus , [sBiometric].[fEmployeeTravelGet](TM.ATTN_DATE,TM.EmployeeId) AS EmployeeTravel,
	ISNULL(ELS.Id,0) AS EmployeeLateStatusId
	FROM #TempMonthTrans TM 
	INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId
	INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId
	LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)
	WHERE 
	TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate 	
	AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
	AND (PresentStatus = @rStatus OR @rStatus='0')
	Order By TM.EmployeeId,TM.Attn_Date
END
GO
PRINT N'Altering [sCertificate].[pRptBonafiedCertificateGet]...';


GO


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

DECLARE @lConfigValue nvarchar(50)

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

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	
	
	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			B.Id,
			B.Number,
			B.AcademicId,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			B.BonafideDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			--OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			--OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			ATM.Title AS AffiliationType,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			@lIsShowPhoto AS IsShowPhoto,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			B.Remark AS ReceiptNo,
			SF.FatherName,
			SA.AdmissionDate,
			DP.Title AS DepartmentName,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4,
			REPLICATE(',',OM.LetterHeadMargin)    AS LetterHeadMargin,
			ISNULL(B.BonafiedReason,'') AS BonafiedReason,
			CT.Title AS Category,
			SF.MotherName,
			C.PermanentStreetOne,
			C.PermanentStreetTwo,
			C.PermanentStreetThree,
			C.PermanentCountry,
			C.PermanentState,
			C.PermanentCity,
			C.PermanentZipCode,
			C.PermanentContactNo,
			C.PresentStreetOne,
			C.PresentStreetTwo,
			C.PresentStreetThree,
			C.PresentCountry,
			C.PresentState,
			C.PresentCity,
			C.PresentContactNo,
			C.PresentZipCode,
			SM.SUId,
			SO.AdhaarNumber,
			CM.DisplayTitle AS ClassName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			OM.PrincipalSignature
			
			
	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
			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
			
			
			
			--INNER JOIN sSetup.tTermMaster TM ON  TM.ID=
	WHERE 
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		--AND ((B.BonafideDate=@rBonafiedDate) OR (ISNULL(@rBonafiedDate,'')=''))
		AND ((B.Number=@rNumber) OR (@rNumber=''))
		AND ((B.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((B.Number <= @rToNo) OR (@rToNo=''))
		AND ((B.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((B.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--Group By B.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
		--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,B.BonafideDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,
		--OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering [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 sSetup.tOrganizationMaster WHERE Id = @rOrgId
DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgId

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

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


GO

ALTER PROCEDURE [sCommon].[pOrgGroupSetupRemove]
	 
	 @rOrgGroupId smallint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
	
	IF EXISTS(SELECT TOP 1 1 FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
	BEGIN
	SELECT -101 AS Result
	RETURN
	END
	
	
	BEGIN TRANSACTION
	 
	EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    




DELETE FROM sAccounting.tAccountingYearMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tAccountMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerGroupMaster  WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransaction WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sActivity.tActivityTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tClubMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tImmunizationChart WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryReferenceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAttendance.tAbsentReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingConductMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingProgressMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingRemarkMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAreaMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tBirthPlaceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCountryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tDistrictMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHobbyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tMotherTongueMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tNationalityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tOccupationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tPreviousSchoolMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tReligionMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tStateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tSurnameMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBehaviourTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlogComment WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogFavorite WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogScope WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircular WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCircularScope WHERE CAST(LEFT(CircularId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularView WHERE CAST(LEFT(CircularId, 4) AS BIGINT) =@rOrgGroupId
DELETE FROM sCommunication.tNews WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tNewsComment WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tNewsScope WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPhotoCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPoll WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPollAnswer WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollMember WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollResult WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQuery WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryAssignedTo WHERE CAST(LEFT(QueryCategoryId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryComment WHERE CAST(LEFT(QueryId, 4) AS BIGINT) =  @rOrgGroupId
DELETE FROM sEExam.tDataBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataSubjectMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionOption WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionParagraph WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateQuestion WHERE CAST(LEFT(TestTemplateId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tStockUomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sGSEB.tActivityGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityIndicatorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tRoomCategoryMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tRoomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tQualificationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tItemMainGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tItemSubGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemCategoryMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tStoreLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAgeGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAuthorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLanguageMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLocationMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookPublisherMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSupplierMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookTagMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tLibraryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tEsiProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tEsiSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayElement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcess WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessElement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessEmployee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetupDependent WHERE CAST(LEFT(PaySetupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcessCharge WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tProfessionalTaxRange WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sProcurement.tVendorCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrganizationTask WHERE CAST(LEFT(OrgGroupId, 4) AS SMALLINT) = @rOrgGroupId
DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRole WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

 
DELETE FROM sStudent.tAdmissionCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTax.tTaxGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteDestinationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tFamiliyCastMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sScholarship.tScholarshipTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgMainGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgSubGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tVisitorGatePass WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollYearMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sActivity.tEventTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRoleDashlet WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId


DELETE FROM sCommon.tFrequencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tRangeDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tRangeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFinanceCommon.tCurrencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierDispatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierReceive WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tBuildingMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tChangeRoom WHERE CAST(LEFT(RoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelAdmission WHERE CAST(LEFT(Hosteld, 4) AS INT) = @rOrgGroupId

DELETE FROM sLibrary.tLibraryAttendance WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineReceive WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tFuelLogs WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tFuelTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleDocumentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTransport.tVehicleDocuments WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenance WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenanceDetail WHERE CAST(LEFT(VehicleMaintenanceId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleTypeMaster WHERE OrgGroupId = @rOrgGroupId

--DELETE FROM sTimetable.tAssignSchoolRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tDivisionTimeOff WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolBuildingMaster WHERE  OrgGroupId = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomMaster WHERE  CAST(LEFT(SchoolBuildingId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tTeacherTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

DELETE FROM sCommunication.tEbook WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tEbookScope WHERE  CAST(LEFT(EbookId, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sActivity.tClubTypeMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tHouseGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryStatusMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroup WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroupMember WHERE  CAST(LEFT(CustomGroupId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sTally.tFeeLedgerMapping WHERE CAST(LEFT(FeeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptBookCompanyMapping WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptPosting WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoom WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoomTimeOff WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tSchoolBuilding WHERE  OrgGroupId = @rOrgGroupId
 DELETE FROM sCommon.tCastCategoryMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tTransportMaster WHERE  OrgGroupId = @rOrgGroupId

DELETE FROM sAlert.tOtherGroupDetail WHERE  CAST(LEFT(OtherGroupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tOtherGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAdmissionQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tCollectionGroupMaster WHERE  CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId

DELETE FROM sHrm.tWorkAreaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItem WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItemSize WHERE  CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sIp.tUniformStock WHERE  CAST(LEFT(UniformSizeId, 4) AS INT) = @rOrgGroupId

DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tReportOrgGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayConfiguration WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sTimetable.tDivisionClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tSubjectClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tTimeTableDetail WHERE CAST(LEFT(TimetableId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeDetail WHERE CAST(LEFT(ExemptionTypeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSecurity.tRoleModulePermission WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId

/* -- Date : 13/06/2016 -- */
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenIssueDetail WHERE CAST(LEFT(CanteenIssueId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tFoodItemMaster WHERE CAST(LEFT(CanteenId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFrontOffice.tLostFoundRegister WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sHostel.tAssetTypeMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tAssignRoomAsset WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tRoomAssetMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tLeaveReasonMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sSetup.tOrgGroupSetting WHERE OrgGroupId = @rOrgGroupId
 
DELETE FROM sStudent.tSUIdConfig WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTimetable.tAssignDivision WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

/* -- Date : 12/08/2016 -- */
DELETE FROM sHostel.tHostelDepositAdd WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositAdjustment WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositRefund WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSystem.tExceptionLog WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 17/09/2016 -- */
DELETE FROM sCommon.tReportClient WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tTempCircularScope WHERE CAST(LEFT(TempCircularId, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sErp.tCustomerMaster WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 05/10/2016 -- */
DELETE FROM sHostel.tAttendanceRegister WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateCommunications WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateImages WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidatePreviousEmployment WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateQualification WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateVacancyCriteriaScore WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tInterviewCriteria WHERE CAST(LEFT(VacancyId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tRecruitmentStatusLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tVacancy WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 24/11/2016 -- */

DELETE FROM siTax.tAssessmentYear WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16 WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16Detail WHERE CAST(LEFT(Form16Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxChallan WHERE CAST(LEFT(AssesmentYearId, 4) AS INT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSlab WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSubGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tPlacementCompanyMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAppraisal.tConductTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sErp.tCustomerActivationLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicyDetail WHERE  CAST(LEFT(IpPolicyId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tTimePolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserPolicy WHERE  CAST(LEFT(TimePolicyId, 4) AS int) = @rOrgGroupId


DELETE FROM sAppraisal.tKPATemplateDetail WHERE CAST(LEFT(KPATemplateId, 4) AS int) = @rOrgGroupId
DELETE FROM sAppraisal.tKPATemplateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayProduct WHERE CAST(LEFT(GatewayConfigurationId, 4) AS int) = @rOrgGroupId
DELETE FROM sOp.tGatewayProductReceiptBookMapping WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tSstockIssueTypeMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sFee.tFeeDepositExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelAttendanceTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseSubTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelGatePassReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformOrderItem WHERE CAST(LEFT(StockItemId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturn WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturnBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentOtherGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentUIdMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAssetManagement.tAssetCheck WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAssetManagement.tAssetInchargeUser WHERE CAST(LEFT(AssetId, 4) AS int) = @rOrgGroupId
DELETE FROM sCanteen.tBreakTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tDailyMenu WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId

DELETE FROM sAlert.tAdVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeAccountMapping WHERE CAST(LEFT(ChargeId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tChargeAccountPosting WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountMapping WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountPosting WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId

DELETE FROM sCommunication.tFeedback WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeDetail WHERE CAST(LEFT(FeedbackAnswerTypeId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAssign WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackFor WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackQuestionResponse WHERE CAST(LEFT(FeedbackResponseId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackResponse WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplate WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplateQuestion WHERE CAST(LEFT(FeedbackTemplateId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tStockReset WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockResetBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tBackupLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSystem.tPortalSync WHERE OrgGroupId = @rOrgGroupId



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

	-- special case will come orgwise and orggroupwise

DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgGroupId 
DELETE FROM sConfig.tConfigurationSetup WHERE SourceTypeId = 2010 AND SourceId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupBatchMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupMaster WHERE Id=@rOrgGroupId



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

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


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

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

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

   SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId
   
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF EXISTS(SELECT 1 from sFee.tChargeReceipt where ReceiptNumber=@rReceiptNumber AND ChargeReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
	END
	ELSE	
		SET @rReceiptNumber = sFee.fChargeReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId)



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

	INSERT INTO sFee.tChargeReceipt
		(
			Id,
			SourceTypeId,
			SourceId,
			GuestName,
			ChargeReceiptBookId,
			Remark,
			ReceiptNumber,
			ReceiptDate,
			PayTypeId,
			ChequeNo,
			BankName,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			OrgId,
			BatchId,
			OrgGroupBatchId,
			ReceiptAmount,
			ChequeDate
		)
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
			@rGuestName,
			@rReceiptBookId,
			@rRemark,
			@rReceiptNumber,
			@rReceiptDate,
			@rPayTypeId,
			@rChequeNo,
			@rBankName,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			@rBatchId,
			@rOrgGroupBatchId,
			@rReceiptAmount,
			@rChequeDate
		)
		             
	END	 
	 ELSE
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tChargeReceipt
	    SET
			SourceTypeId=@rSourceTypeId,
			SourceId=@rSourceId,
			GuestName=@rGuestName,
			ChargeReceiptBookId=@rReceiptBookId,
			Remark=@rRemark,
			ReceiptNumber=@rReceiptNumber,
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeNo=@rChequeNo,
			BankName=@rBankName,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ReceiptAmount=@rReceiptAmount,
			ChequeDate=@rChequeDate
	      WHERE Id = @rId 	   
		  SELECT @lNextNumber AS Result	  
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pChargeReceiptListGet]...';


GO

ALTER PROCEDURE [sFee].[pChargeReceiptListGet]
	 
	 --@rReceiptNumber int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSourceTypeId smallint,
	 @rSourceCode nvarchar(20),
	 @rGuestName nvarchar(200),
	 @rFromDate date,
	 @rToDate date,
	 @rFromNo int,
	 @rToNo int,
	 @rReceiptBookId int,
	 @rChargeCategoryId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rOrgGroupBatchId int,
	 @rDepartmentId int = 0,
	 @rStudentCode nvarchar(20) = '',
	 @rOrgGroupId int=0,
	 @rStatusId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

		--select 
		
		--		'' AS Builder1,
		--		'' AS Builder2,
		--		'' AS Id,
		--		'' AS SourceType,
		--		'' AS SourceTypeId
		--		,'' AS GuestName
		--		,'' AS ReceiptNumber
		--		,'' AS ReceiptDate
		--		,'' AS Amount
		--		,'' AS ChargeCategory
		--		,'' AS ReceiptBook
		--		,'' AS ChargeCategoryId
		--		,'' As ReceiptBookId
		--		,'' AS OrgId
		--		,'' AS School
		--		,'' AS OrgGroupId
		--		,'' AS ChargeId








	 ----IF(@rIsSearch=1)
		----BEGIN
			SET @rSourceCode = sCommon.fSearchStringGet(@rSourceCode)
			SET @rGuestName = sCommon.fSearchStringGet(@rGuestName)
		--Declare @rSourceTypeId smallint
		--select @rSourceTypeId=SourceTypeId from sFee.tChargeReceipt where ReceiptNumber=@rReceiptNumber and OrgId=@rOrgId
		--END
IF @rSourceTypeId=95
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = @rSourceTypeId) 
       --AND EM.StatusId=7
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
     
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,'')=''))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			And (CR.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			AND ((EM.StatusId=@rStatusId) OR (@rStatusId=0))
			group by CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
END
ELSE IF @rSourceTypeId=2001
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001 
       --AND SA.StatusId=1
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
			group by CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CM.ChargeCategoryId,CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle
END
ELSE IF @rSourceTypeId=3
BEGIN
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
			CR.Id,
			'Other' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			CR.GuestName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				(ISNULL(CR.SourceTypeId,0)=0)
			AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			--AND (ISNULL(@rSourceCode,'') = '')
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
END	
ELSE
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = 95) 
       --AND EM.StatusId=7
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			group by CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CM.ChargeCategoryId,CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle
			
			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001 
       --AND SA.StatusId=1
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
				((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			group by CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
			
			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Other' as SourceType,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			CR.GuestName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
       INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
       --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
       --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			(ISNULL(CR.SourceTypeId,0)=3)
			AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			--AND (ISNULL(@rSourceCode,'') = '')
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
END
END
GO
PRINT N'Altering [sFee].[pCollectionGroupMasterAdd]...';


GO
ALTER PROCEDURE [sFee].[pCollectionGroupMasterAdd]
	 
	 
		@rOrgGroupBatchId int,
        @rId int,
        @rCode nvarchar(20),
        @rTitle nvarchar(100),
        @rStartDate date,
        @rEndDate date,
        @rRemark nvarchar(500),
        @rIsObsolete bit,
        @rOrderIndex smallint,
        @rOrgGroupId int,
        @rReceiptBookId int=0,
        @rFooterRemark1 nvarchar(200)='',
        @rFooterRemark2 nvarchar(200)='',
        @rFeePeriod nvarchar(200)='',
        @rIsDisplayCashDetailInFolio bit=0,
        @rReportId int=0,
        @rIsOnPrePrinted bit=0
        
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId)
			BEGIN
			SELECT -101 as Result
			RETURN
		END 
	
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId)
			BEGIN
			SELECT -102 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE  Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId AND Id<>@rId)
		BEGIN
			SELECT -101 as Result
			RETURN
		END	
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE  Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId AND Id<>@rId)
		BEGIN
			SELECT -102 as Result
			RETURN
		END 

	END
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tCollectionGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFee.tCollectionGroupMaster
		(
			OrgGroupBatchId,
			Id,
			Code,
			Title,
			StartDate,
			EndDate,
			Remark,
			IsObsolete,
			OrderIndex,
			ReceiptBookId,
			FooterRemark1,
			FooterRemark2,
			FeePeriod,
			IsDisplayCashDetailInFolio,
			ReportId,
			IsOnPrePrinted
		)
	VALUES
		(
			@rOrgGroupBatchId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rStartDate,
			@rEndDate,
			@rRemark,
			@rIsObsolete,
			@rOrderIndex,
			@rReceiptBookId,
			@rFooterRemark1,
			@rFooterRemark2,
			@rFeePeriod,
			@rIsDisplayCashDetailInFolio,
			@rReportId,
			@rIsOnPrePrinted
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tCollectionGroupMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			Remark=@rRemark,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
			ReceiptBookId=@rReceiptBookId,
			FooterRemark1=@rFooterRemark1,
			FooterRemark2=@rFooterRemark2,
			FeePeriod=@rFeePeriod,
			IsDisplayCashDetailInFolio=@rIsDisplayCashDetailInFolio,
	        ReportId=@rReportId,
	        IsOnPrePrinted=@rIsOnPrePrinted
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	
	if not exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGroupId)
	BEGIN
		INsert Into sSystem.tPortalSync
		(
			OrgGroupId,
			FeeChange
		)
		Values
		(
			@rOrgGroupId,1
		)
	END
	ELse
	BEGIN
		Update sSystem.tPortalSync
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
	
	END
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pDepositePostingAdd]...';


GO

ALTER PROCEDURE [sFee].[pDepositePostingAdd]
	 
	        @rAccount nvarchar(100),
	        @rAccountingYear nvarchar(100),
	        @rOrgGroupId int,
            
            @rNarration nvarchar(150),  
            @rVoucherTypeId tinyint,
            @rIsProfitAndLoss int,
            @rRepeatLedger int,
            @rCreatedUserId bigint,
            @rCreditLedgerId int,
            @rDebitLedgerId int,
            @rDepositeHeadId int ,
            
			@rPayTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
		
		
	DECLARE @lNextNumber BIGINT
	DECLARE @lNextNumberPosting INT
	DECLARE @1AccountId int 
	DECLARE @1AccountYearId int 
	DECLARE @lVoucherNumber bigint
	
    SELECT @1AccountId = AYM.AccountId, @1AccountYearId = AYM.Id FROM sAccounting.tAccountingYearMaster AYM 
    INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
    WHERE AM.Title= sSetup.fPortalXMLTagsReplaceReverse(@rAccount) AND AYM.Title = @rAccountingYear
    
    SELECT @lVoucherNumber = ISNULL(Max(T.VoucherNumber),0) + 1 FROM sAccounting.tTransaction T
	WHERE VoucherTypeId=@rVoucherTypeId AND AccountingYearId = @1AccountYearId
    
    IF NOT EXISTS (SELECT 1 FROM sFee.tDepositeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate= sCommon.fGetDate() AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId 
    AND DebitLedger = @rDebitLedgerId AND DepositeHeadId=@rDepositeHeadId)
    BEGIN
		SELECT @lNextNumberPosting = ISNULL(MAX(Id),0) + 1 FROM sFee.tDepositeAccountPosting
		INSERT INTO sFee.tDepositeAccountPosting
		(
			Id,
			AccountYearId,
			AccountId,
			TransactionDate,
			VoucherTypeId,
			CreditLedger,
			DebitLedger,
			DepositeHeadId
		)
		VALUES
		(
			@lNextNumberPosting,
			@1AccountYearId,
			@1AccountId,
			 sCommon.fGetDate(),
			@rVoucherTypeId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rDepositeHeadId
		)
    END
	
	SELECT @lNextNumberPosting = Id FROM sFee.tDepositeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate= sCommon.fGetDate() AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId
    AND DebitLedger = @rDebitLedgerId AND DepositeHeadId=@rDepositeHeadId
  
	IF EXISTS (SELECT 1 FROM [sAccounting].[tTransaction] WHERE SOURCEID=@lNextNumberPosting)
	BEGIN
		SELECT 101 AS Result
		COMMIT TRANSACTION				
		RETURN 
	END
    
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id],
			    [OrgGroupId],
			    [AccountingYearId],
			    [TransactionDate],
			    [Narration],
			    [VoucherNumber],
			    [VoucherTypeId],
			    [IsProfitAndLoss],
			    [RepeatLedger],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [AccountId],
			    [SourceTypeId],
			    [SourceId],
			    [ChequeNo],
			    [BankName],
			    [ChequeDate],
			    [ChequeClearDate],
			    [PayTypeId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rOrgGroupId,
			    @1AccountYearId,
			     sCommon.fGetDate(),
			    @rNarration,
			    @lVoucherNumber,
			    @rVoucherTypeId,
			    @rIsProfitAndLoss,
			    @rRepeatLedger,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @1AccountId,
			    1,
			    @lNextNumberPosting,
			    '',
			    '',
			    '',
			    '',
			    @rPayTypeId
			   )
		    SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pExemptionTypeDetailAdd]...';


GO

ALTER PROCEDURE [sFee].[pExemptionTypeDetailAdd]

           @rExemptionTypeId int,
           @rStrXml nvarchar(MAX),
			@rOrgGroupId int=0
		  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	

BEGIN
	
	DELETE FROM sFee.tExemptionTypeDetail WHERE ExemptionTypeId = @rExemptionTypeId
	
	INSERT INTO sFee.tExemptionTypeDetail
		(
			ExemptionTypeId,
		    FeeId,
		    ExemptionPercentage
		)
		
		SELECT		
			
			@rExemptionTypeId,
			FeeId,
			ExemptionPercentage
						
		FROM OPENXML (@loDoc, '/Table/ExemptionTypeDetail', 1)
		WITH 
			 ( 
			    FeeId int,
			    ExemptionPercentage decimal(8,2)
			  ) 
		
        SELECT 1 AS Result
	END	 
	
	If NOt Exists(Select 1 from sSystem.tPortalSync Where OrgGroupId=@rOrgGroupId)
	BEGIN
	Insert Into sSystem.tPortalSync
		(
			OrgGroupId,
			FeeChange
		)
		Values
		(
			@rOrgGroupId,
			1
		)
	END
	ELse
	BEGIN
		Update sSystem.tPortalSync
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
	
	END
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sFee].[pExemptionTypeMasterAdd]...';


GO

ALTER PROCEDURE [sFee].[pExemptionTypeMasterAdd]
	 
	        @rId int,
	        @rCode nvarchar(20),
	        @rNumber smallint,
            @rTitle nvarchar(100),
            @rOrgGroupId int,
            @rIsObsolete bit,
            @rOrderIndex smallint,
            @rCreatedUserId bigint,
            @rCalculationTypeId tinyint=0
            
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM sFee.tExemptionTypeMaster WHERE Code=@rCode AND OrgGroupId=@rOrgGroupId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END 
	
		IF EXISTS(SELECT Id FROM sFee.tExemptionTypeMaster WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT Id FROM sFee.tExemptionTypeMaster WHERE Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF EXISTS(SELECT Id FROM sFee.tExemptionTypeMaster WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END

	END

	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tExemptionTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFee.tExemptionTypeMaster
			   (
			    Id,
			    Code,
			    Number,
			    Title,
			    OrgGroupId,
			    IsObsolete,
			    OrderIndex,
			    CreatedUserId,
			    CreatedDateTime,
			    UpdatedUserId,
			    UpdatedDateTime,
			    CalculationTypeId
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rCode,
			    @rNumber,
			    @rTitle,
			    @rOrgGroupId,
			    @rIsObsolete,
			    @rOrderIndex,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    0,
			    sCommon.fGetDate(),
			    @rCalculationTypeId
			   )
		    SELECT @lNextNumber AS Result
       
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sFee.tExemptionTypeMaster
	    SET
			  Code=@rCode,
			  Number=@rNumber,
	          Title=@rTitle,
	          IsObsolete=@rIsObsolete,
	          OrderIndex=@rOrderIndex,
              UpdatedUserId=@rCreatedUserId,
              UpdatedDateTime = sCommon.fGetDate(),
              CalculationTypeId=@rCalculationTypeId          
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result

	 END  	
	
	If Not exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrggroupId)
	BEGIN
	Insert INto sSystem.tPortalSync
	(
		OrgGroupId,
		FeeChange
	)
	Values
	(
		@rORgGRoupId,
		1
	)
	END
	Else
	BEGIN
		Update sSystem.tPortalSync
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
	END
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeeHeadMasterAdd]...';


GO

ALTER PROCEDURE [sFee].[pFeeHeadMasterAdd]
	 
	        @rId int
	       ,@rNumber int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rOrderIndex int
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sFee.tFeeHeadMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tFeeHeadMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If Exists(select Id from sFee.tFeeHeadMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tFeeHeadMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sFee.tFeeHeadMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End 
		If Exists(select Id from sFee.tFeeHeadMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If  Exists(select Id from sFee.tFeeHeadMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from sFee.tFeeHeadMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
BEGIN
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sFee.tFeeHeadMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tFeeHeadMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sFee].[tFeeHeadMaster]
			   (
			    [Id]
			   ,[Number]  
			   ,[Code]
			   ,[Title]
			   ,[OrderIndex]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rNumber
			   ,@rCode
			   ,@rTitle
			   ,@rOrderIndex
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   )
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tFeeHeadMaster]
	    SET
			  Number=@rNumber
	         ,Code=@rCode
	         ,Title=@rTitle
	         ,OrderIndex=@rOrderIndex
             ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	
	 END  
	      SELECT @lNextNumber AS Result
	      
	      If Not Exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGroupId)
	      BEGIN
			Insert Into sSystem.tPortalSync
			(
				OrgGroupId,
				FeeChange
			)
			Values
			(
				@rOrgGroupId,
				1
			)
	      END
	      Else
	      BEGIN
			Update sSystem.tPortalSync
			Set
				FeeChange=1
			Where OrgGroupId=@rOrgGroupId
	      END
	      
			COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeeMainGroupOrgGroupwiseAdd]...';


GO

ALTER PROCEDURE [sFee].[pFeeMainGroupOrgGroupwiseAdd]
	
	@rMainGroupOrgGroupwiseImpXml [nvarchar](max),
	@rOrgGroupId int
	--,
	--@rFeeMainGroupId int,
	--@rFeeHeadId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rMainGroupOrgGroupwiseImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId=@rOrgGroupId
	
	 INSERT INTO sFee.tFeeMainGroupOrgGroupwise
		(
			OrgGroupId,
			FeeMainGroupId,
			FeeHeadId
			)
		SELECT
			OrgGroupId,
			FeeMainGroupId,
			FeeHeadId
		FROM OPENXML (@loDoc, '/Table/FeeMainGroupOrgGroupwise', 1)
		WITH ( 
				OrgGroupId int,
				FeeMainGroupId int,
				FeeHeadId int
			  ) 
		
	   SELECT 1 AS Result
	   
	   if Not Exists(Select 1 from sSystem.tPortalSync Where OrgGRoupId=@rOrgGRoupId)
	   BEGIN
		Insert into sSystem.tPortalSync
		(
			OrgGroupId,
			FeeChange
		)
		Values
		(
			@rOrgGroupId,
			1
		)
		END
		Else
		BEGIN
			Update sSystem.tPortalSync
			Set
				FeeChange=1
			Where OrgGroupId=@rOrgGroupId
		END
	    
	   EXEC sp_xml_removedocument @loDoc
	   
	   COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeeMasterAdd]...';


GO

ALTER PROCEDURE [sFee].[pFeeMasterAdd]
	 
	        @rId int
	       ,@rNumber int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rFeeHeadId int
           ,@rOrderIndex int
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sFee.tFeeMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tFeeMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If Exists(select Id from sFee.tFeeMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tFeeMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sFee.tFeeMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End 
		If Exists(select Id from sFee.tFeeMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If  Exists(select Id from sFee.tFeeMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from sFee.tFeeMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End


	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
BEGIN
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sFee.tFeeMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tFeeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sFee].[tFeeMaster]
			   (
			    [Id]
			   ,[Number]  
			   ,[Code]
			   ,[Title]
			   ,[FeeHeadId]
			   ,[OrderIndex]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFeeHeadId
			   ,@rOrderIndex
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   )
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tFeeMaster]
	    SET
			  Number=@rNumber
	         ,Code=@rCode
	         ,Title=@rTitle
	         ,FeeHeadId=@rFeeHeadId
	         ,OrderIndex=@rOrderIndex
             ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	
	 END  
	      SELECT @lNextNumber AS Result
	      
	      if NOT Exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGroupId)
	      BEGIN
			insert into sSystem.tPortalSync
			(
				OrgGroupId,
				FeeChange
			)
			Values
			(
				@rOrgGroupId,
				1
			)
	      END
	      Else
	      BEGIN
			Update sSystem.tPortalSync
			Set
				FeeChange=1
			Where ORgGroupId=@rOrgGRoupId
	      END
			COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeePostingAdd]...';


GO
ALTER PROCEDURE [sFee].[pFeePostingAdd]
	 
	        @rAccount nvarchar(100),
	        @rAccountingYear nvarchar(100),
	        @rOrgGroupId int,
            @rTransactionDate date,
            @rNarration nvarchar(150),  
            @rVoucherTypeId tinyint,
            @rIsProfitAndLoss int,
            @rRepeatLedger int,
            @rCreatedUserId bigint,
            @rCreditLedgerId int,
            @rDebitLedgerId int,
            @rReceiptBookId int,
            @rChequeNo nvarchar(10),
			@rBankName nvarchar(50),
			@rChequeDate datetime,
			@rChequeClearDate datetime=NULL,
			@rPayTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
		
		
	DECLARE @lNextNumber BIGINT
	DECLARE @lNextNumberPosting INT
	DECLARE @1AccountId int 
	DECLARE @1AccountYearId int 
	DECLARE @lVoucherNumber bigint
	
    SELECT @1AccountId = AYM.AccountId, @1AccountYearId = AYM.Id FROM sAccounting.tAccountingYearMaster AYM 
    INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
    WHERE AM.Title= sSetup.fPortalXMLTagsReplaceReverse(@rAccount) AND AYM.Title = @rAccountingYear
    
    SELECT @lVoucherNumber = ISNULL(Max(T.VoucherNumber),0) + 1 FROM sAccounting.tTransaction T
	WHERE VoucherTypeId=@rVoucherTypeId AND AccountingYearId = @1AccountYearId
    
    IF NOT EXISTS (SELECT 1 FROM sFee.taccountposting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId 
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId And ChequeNo=@rChequeNo AND BankName=@rBankName)
    BEGIN
		SELECT @lNextNumberPosting = ISNULL(MAX(Id),0) + 1 FROM sFee.tAccountPosting
		INSERT INTO [sFee].[tAccountPosting]
		(
			Id,
			AccountId,
			AccountYearId,
			TransactionDate,
			VoucherTypeId,
			CreditLedger,
			DebitLedger,
			ReceiptBookId,
			ChequeNo,
			BankName
		)
		VALUES
		(
			@lNextNumberPosting,
			@1AccountId,
			@1AccountYearId,
			@rTransactionDate,
			@rVoucherTypeId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rReceiptBookId,
			@rChequeNo,
			@rBankName
		)
    END
	
	SELECT @lNextNumberPosting = Id FROM sFee.taccountposting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId
  
	IF EXISTS (SELECT 1 FROM [sAccounting].[tTransaction] WHERE SOURCEID=@lNextNumberPosting)
	BEGIN
		SELECT 101 AS Result
		COMMIT TRANSACTION				
		RETURN 
	END
    
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id],
			    [OrgGroupId],
			    [AccountingYearId],
			    [TransactionDate],
			    [Narration],
			    [VoucherNumber],
			    [VoucherTypeId],
			    [IsProfitAndLoss],
			    [RepeatLedger],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [AccountId],
			    [SourceTypeId],
			    [SourceId],
			    [ChequeNo],
			    [BankName],
			    [ChequeDate],
			    [ChequeClearDate],
			    [PayTypeId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rOrgGroupId,
			    @1AccountYearId,
			    @rTransactionDate,
			    @rNarration,
			    @lVoucherNumber,
			    @rVoucherTypeId,
			    @rIsProfitAndLoss,
			    @rRepeatLedger,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @1AccountId,
			    1,
			    @lNextNumberPosting,
			    @rChequeNo,
			    @rBankName,
			    @rChequeDate,
			    @rChequeClearDate,
			    @rPayTypeId
			   )
		    SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeePostingDetailGet]...';


GO

ALTER PROCEDURE [sFee].[pFeePostingDetailGet]
				
		  -- @rClassId int,
           @rAdmissionCategoryId int=0,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptDate date,
           @rReceiptDateTo date
            
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			
			AM.FeeSetupId,
			AMast.Id AS AccountId,
			AMast.Title AS AccountName,
			AM.AccountingYearId,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			AM.PayTypeId,
			PTM.Title AS PayTypeName,
			FM.Id AS FeeId,
			FM.Title AS FeeTitle,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FS.ReceiptBookId AS ReceiptBookId,
			RBM.Title AS ReceiptBookTitle,
			SUM(RD.Amount) AS ReceiptAmount
			
  FROM 
			sFee.tAccountMapping AM
			INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
			INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate
				AND R.ReceiptDate <= @rReceiptDateTo				
			INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
			--AND (FS.ClassId=@rClassId) 
				AND (FS.AdmissionCategoryId=@rAdmissionCategoryId Or @rAdmissionCategoryId = 0) 
				AND (R.OrgGroupBatchId=@rBatchId)
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId 
		    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		    INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId	
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = AM.PayTypeId
WHERE 
			FM.OrgGroupId=@rOrgGroupId
			
			GROUP BY 
			AMast.Id,AMast.Title,AM.FeeSetupId,AM.AccountingYearId,AYM.Title,AM.CreditLedgerId,CLM.Title,
			AM.DebitLedgerId,DLM.Title,AM.PayTypeId,PTM.Title,FM.Id,FM.Title,FHM.Id,FHM.Title,FS.ReceiptBookId,
			RBM.Title
END
GO
PRINT N'Altering [sFee].[pFeeSetupAdd]...';


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

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

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

	INSERT INTO sFee.tFeeSetup
		(
		   Id,
           ClassId,
           AdmissionCategoryId,
           BatchId,
           FeeId,
           IsOptional,
           IsVariable,
           Amount,
           StartDate,
           EndDate,
           ReceiptBookId,
           CreatedUserId,
           CreatedDateTime,
           IsServiceTax,
           CollectionGroupId
        )
	VALUES
		(
			@lNextNumber,
			@rClassId,
			@rAdmissionCategoryId,
            @rBatchId,
            @rFeeId,
            @rIsOptional,
            @rIsVariable,
            @rAmount,
            @rStartDate,
            @rEndDate,
            @rReceiptBookId,
            @rCreatedUserId,
			sCommon.fGetDate(),
			@rIsServiceTax,
			@rCollectionGroupId
		)
		SELECT 1 AS Result
		             
	END	 
	 ELSE
	 BEGIN
	 
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tFeeSetup
	    SET
			 --ClassId=@rClassId,
			 --AdmissionCategoryId=@rAdmissionCategoryId,
    --         BatchId=@rBatchId,
             IsOptional=@rIsOptional,
             IsVariable=@rIsVariable,
             Amount=@rAmount,
             StartDate=@rStartDate,
             EndDate=@rEndDate,
             ReceiptBookId=@rReceiptBookId,
             UpdatedUserId=@rUpdatedUserId,
			 UpdatedDateTime=sCommon.fGetDate(),
			 IsServiceTax=@rIsServiceTax,
			 CollectionGroupId=@rCollectionGroupId
	      WHERE (Id = @rId)
	       --AND (FeeId=@rFeeId) 
	      SELECT 11 AS Result   
	 END  
	
	If Not Exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGRoupId)
	BEGIN
		Insert INto sSystem.tPortalSync 
		(
			OrgGRoupId,
			FeeChange
		)
		Values
		(
			@rOrgGRoupId,
			1
		)
	END
	Else
	BEGIN
		Update sSystem.tPortalSync 
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
		
	END
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sFee].[pReceiptAdd]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN
	BEGIN TRY

	  SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId
	
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
	END
	ELSE	
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId)

EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rIsCreated = @lIsCreated OUTPUT
 	IF(@lIsCreated = 1)
 		BEGIN
			SELECT -501 AS Result
			RETURN
		END
 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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


	INSERT INTO sFee.tReceipt
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptNumber,
		   ReceiptDate,
		   ReceiptAmount,
		   TotalReceiptAmount,
		   DiscountAmount,
		   PayTypeId,
		   ChequeNo,
		   BankName,
		   ReceiptBookId,
		   Remark,
		   IsObsolete,
		   BatchId,
		   CreatedUserId,
		   CreatedDateTime,
		   OrgGroupBatchId,
		   ChequeDate,
		   FeeInvoiceId,
		   CollectionGroupId
        )
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
		    @rReceiptNumber,
		    @rReceiptDate,
		    @rReceiptAmount,
		    @rTotalReceiptAmount,
		    @rDiscountAmount,
		    @rPayTypeId,
		    @rChequeNo,
		    @rBankName,
		    @rReceiptBookId,
		    @rRemark,
		    @rIsObsolete,
		    @rBatchId,
		    @rCreatedUserId,
		    sCommon.fGetDate(),
		    @rOrgGroupBatchId,
		    @rChequeDate,
		    @rFeeInvoiceId,
		    @rCollectionGroupId
		)
		
		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		
	FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
		IF (@rCharge > 0)
		BEGIN
		EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
		END
	
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) FROM sFee.tReceiptBookMaster where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
		EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
		END
 END 
	ELSE
	BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
	SELECT @rId AS RESULT
	END 
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pReceiptBookMasterAdd]...';


GO

ALTER PROCEDURE [sFee].[pReceiptBookMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rFullTitle nvarchar(200)
           ,@rAddress1 nvarchar(200)
           ,@rAddress2 nvarchar(200)
           ,@rBankAccountNumber nvarchar(50)
           ,@rIsObsolete bit
           ,@rRemark1 nvarchar(500)
           ,@rRemark2 nvarchar(500)
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
           ,@rIsOnPrePrinted bit
           ,@rReportId int
           ,@rIsSupressLogo bit
           ,@rOrderIndex int
           ,@rIsDisplaySchoolName bit
           ,@rIsMonthDetailOnly bit
           ,@rIsServiceTaxApplicable bit
           ,@rServiceTaxPercentage decimal(6,2)
           ,@rBankName nvarchar(150)=''
           ,@rIsFeeInvoiceHeadwise bit = 0
           ,@rGroupTitle nvarchar(200)=''
           ,@rIsSuppressFeeDetail bit=0
		   ,@rReceiptLogo varbinary(max)=NULL
		   ,@rHeaderDisplayId tinyint
		   ,@rReceiptBookHeader varbinary(max)=NULL
		   ,@rFeeInvoiceHeaderDisplayId tinyint
		   ,@rFeeInvoiceHeader varbinary(max)=NULL
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
If Exists(select top(1)* from sFee.tReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId) 
BEGIN
	If NOT Exists(select top(1)* from sFee.tReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id=@rId)
	BEGIN
		select -101 as Result
	END
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete      
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo   
             ,OrderIndex=@rOrderIndex
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,IsMonthDetailOnly=@rIsMonthDetailOnly
             ,IsServiceTaxApplicable=@rIsServiceTaxApplicable
			 ,ServiceTaxPercentage=@rServiceTaxPercentage
			 ,BankName=@rBankName
			 ,IsFeeInvoiceHeadwise=@rIsFeeInvoiceHeadwise
			 ,GroupTitle =@rGroupTitle
			 ,IsSuppressFeeDetail=@rIsSuppressFeeDetail
			 ,ReceiptLogo = @rReceiptLogo
			 ,ReceiptBookHeader=@rReceiptBookHeader
			 ,HeaderDisplayId=@rHeaderDisplayId
			  ,FeeInvoiceHeader=@rFeeInvoiceHeader
			 ,FeeInvoiceHeaderDisplayId=@rFeeInvoiceHeaderDisplayId
			 
             
	      WHERE Id = @rId 	 
	      SELECT @lNextNumber AS Result
	 END  
END
ELSE
BEGIN
IF(@rId = 0)	
BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tReceiptBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sFee].[tReceiptBookMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[FullTitle]
			   ,[Address1] 
			   ,[Address2] 
			   ,[BankAccountNumber] 
			   ,[IsObsolete]
			   ,[Remark1] 
			   ,[Remark2] 
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[OrgGroupId]
			   ,IsOnPrePrinted
			   ,ReportId
			   ,IsSupressLogo
			   ,OrderIndex
			   ,IsDisplaySchoolName
			   ,IsMonthDetailOnly
			   ,IsServiceTaxApplicable
			   ,ServiceTaxPercentage
			   ,BankName
			   ,IsFeeInvoiceHeadwise
			   ,GroupTitle
			   ,IsSuppressFeeDetail
			   ,ReceiptLogo
			   ,HeaderDisplayId
			   ,ReceiptBookHeader
			   ,FeeInvoiceHeader
			   ,FeeInvoiceHeaderDisplayId
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFullTitle
			   ,@rAddress1
			   ,@rAddress2
			   ,@rBankAccountNumber
			   ,@rIsObsolete
			   ,@rRemark1
			   ,@rRemark2
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rIsOnPrePrinted
			   ,@rReportId
			   ,@rIsSupressLogo
			   ,@rOrderIndex
			   ,@rIsDisplaySchoolName
			   ,@rIsMonthDetailOnly
			   ,@rIsServiceTaxApplicable
			   ,@rServiceTaxPercentage
			   ,@rBankName
			   ,@rIsFeeInvoiceHeadwise
			   ,@rGroupTitle
			   ,@rIsSuppressFeeDetail
			   ,@rReceiptLogo
			   ,@rHeaderDisplayId
			   ,@rReceiptBookHeader
			   ,@rFeeInvoiceHeader
			   ,@rFeeInvoiceHeaderDisplayId
			   
			   
			   )
			   
 
INSERT INTO sSecurity.tUserAccess
           (
            SourceTypeId
            ,SourceId
           ,[UserId]
           
           )
SELECT 
		   2013
		   ,@lNextNumber
		  ,@rCreatedUserId
			   
			   
		    SELECT @lNextNumber AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete          
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2                     
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()   
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo
             ,OrderIndex=@rOrderIndex              
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,IsMonthDetailOnly=@rIsMonthDetailOnly
             ,IsServiceTaxApplicable=@rIsServiceTaxApplicable
			 ,ServiceTaxPercentage=@rServiceTaxPercentage
			 ,BankName=@rBankName
			 ,IsFeeInvoiceHeadwise=@rIsFeeInvoiceHeadwise
			 ,GroupTitle =@rGroupTitle
			 ,IsSuppressFeeDetail=@rIsSuppressFeeDetail
			 ,ReceiptLogo = @rReceiptLogo
			 ,HeaderDisplayId=@rHeaderDisplayId
			 ,ReceiptBookHeader=@rReceiptBookHeader
              ,FeeInvoiceHeaderDisplayId=@rFeeInvoiceHeaderDisplayId
			 ,FeeInvoiceHeader=@rFeeInvoiceHeader
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	 END  
		
	
	END
	If Not Exists(Select 1 from sSystem.tPortalSync where OrgGRoupId=@rOrgGroupId)
	BEGIN
	Insert into sSystem.tPortalSync
	(
		OrgGroupId,
		FeeChange
	)
	Values
	(
		@rOrgGroupId,
		1
	)
	 
	END
	
	Else
	BEGIN
		Update sSystem.tPortalSync 
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
	END
	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pRptChargeReceiptListGet]...';


GO
ALTER PROCEDURE [sFee].[pRptChargeReceiptListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSourceTypeId smallint,
	 @rSourceCode nvarchar(20),
	 @rGuestName nvarchar(200)='',
	 @rFromDate date,
	 @rToDate date,
	 @rFromNo int,
	 @rToNo int,
	 @rReceiptBookId int,
	 @rChargeCategoryId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rOrgGroupBatchId int,
	 @rDepartmentId int = 0,
	 @rStudentCode nvarchar(20) = '',
	 @rIsDetail bit=0,
	 @rCreatedUserName nvarchar(100)='',
	 @rPayTypeId int=0,
	 @rOrgGroupId int=0,
	 @rStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 		
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			CR.ReceiptNumber,
			CR.ReceiptDate,
		    -- For Type 
			(CASE WHEN CR.SourceTypeId = 95 THEN	'Employee'
			 WHEN CR.SourceTypeId = 2001 THEN	'Student'
			 ELSE 'Other' END) AS TypeName,
			-- For Name
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Name 
			WHEN CR.SourceTypeId = 3 THEN CR.GuestName
			WHEN CR.SourceTypeId = 95 THEN EM.EmployeeName
			END ) AS Name, 
			-- For Code
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Code 
			WHEN CR.SourceTypeId = 95 THEN EM.Code
			END ) AS Code,
			-- For Class Department
			(CASE WHEN CR.SourceTypeId = 95 THEN EM.DepartmentName
			WHEN CR.SourceTypeId = 2001 THEN (SA.ClassName + ' - '+ SA.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
			SA.RollNo,
			PTM.Title AS PayType,
			ISNULL(CR.ChequeNo,'') AS ChequeNo,
			ISNULL(CR.BankName,'') AS BankName,
			CR.Remark,
			CR.CreatedUserId,
			U.DisplayTitle AS UserName,
			CR.SourceTypeId,
			ISNULL(RBM.Id,0) AS ChargeReceiptBookId,
			ISNULL(RBM.Title,'') AS ChargeReceiptBookName,
			ISNULL(OM.Title,'') AS OrganizationName,
			CR.ReceiptAmount
			
	FROM 
			sFee.tChargeReceipt CR
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=CR.PayTypeId
			INNER JOIN sFee.tChargeReceiptBookMaster RBM 
				ON RBM.Id=CR.ChargeReceiptBookId
			INNER JOIN sSecurity.tUser U
				ON U.Id=CR.CreatedUserId
			LEFT JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId = 2001	
			LEFT JOIN sHrm.vExtEmployeeMaster EM
				ON EM.Id=CR.SourceId AND CR.SourceTypeId = 95	
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=SA.OrgId				
	WHERE 
			((CR.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
			--AND (((@rSourceTypeId =2001 OR(@rSourceTypeId=0)) AND SA.Name like @rGuestName) 
			--	OR (ISNULL(@rGuestName,'')='') OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND EM.EmployeeName LIKE @rGuestName) OR (ISNULL(@rGuestName,'')='') 
			--	OR ((@rSourceTypeId =3 OR (@rSourceTypeId=0)) AND CR.GuestName LIKE @rGuestName) OR (ISNULL(@rGuestName,'')=''))
            AND (((@rSourceTypeId =2001 OR(@rSourceTypeId=0)) AND SA.Code LIKE @rStudentCode) OR (ISNULL(@rStudentCode,'')='') 
				OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND EM.Code LIKE @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,'')=''))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			And (CR.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CR.PayTypeId = @rPaytypeId OR @rPaytypeId=0)
			AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
			ORDER BY CR.ReceiptNumber
END
GO
PRINT N'Altering [sFee].[pRptSchoolwiseChargeSummaryGet]...';


GO



ALTER PROCEDURE [sFee].[pRptSchoolwiseChargeSummaryGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rChargeCategoryId int,
	 @rDepartmentId int,
	 @rOrgGroupId int=0,
	 @rStatusId int=0
	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

 	SELECT Distinct
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.OrgGroupId,
			CM.Title AS ChargeName,
			CM.Id AS ChargeId,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			CCM.Id AS ChargeCategoryId,
			CCM.Title AS ChargeCategory,
			CM.ChargeAmount
      
	FROM 
			sFee.tChargeMaster CM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=CM.OrgGroupId
			INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id 
	WHERE 
			
			CM.IsObsolete=0
			AND (OM.Id=@rOrgId OR @rOrgId=0)
			AND (CM.ChargeCategoryId=@rChargeCategoryId OR @rChargeCategoryId=0)
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (CM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId=0)
		
END
GO
PRINT N'Altering [sFee].[pRptStudentDepositListGet]...';


GO

ALTER PROCEDURE [sFee].[pRptStudentDepositListGet]
          
          @rOrgGroupId smallint,
		   @rOrgId int,          
           @rDepositHeadId int=0,         
           @rFromDate date='',
           @rToDate date='',        
           --@rCode nvarchar(20)='',          
           @rStudentName nvarchar(100)='',
		  @rStudentCode nvarchar(100)='',
		  @rClassId int=0,
		  @rDivisionId int=0,
		  @rIsBasedOnSUId bit = 0,
		  @rDepartmentId int=0,
		  @rSUId nvarchar(20)='',
		  @rBatchId int=0,
		  @rBuilder1 nvarchar(max)='',
	      @rBuilder2 nvarchar(max)=''
	   
           
AS
SET NOCOUNT ON
 
BEGIN
SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rDepositHeadId AS DepositHeadId,
		--DHM.Title AS DepositHeadName,
		(SELECT [sFee].[fDepositHeadNameGet](@rDepositHeadId)) AS DepositHeadName,
		ISNULL(SA.StudentId,0) as StudentId,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		ISNULL(D.TotalDeposit,0) AS Deposit,
		ISNULL(A.TotalAdjustment,0) AS Adjustment,
		ISNULL(R.TotalRefund,0) Refund,
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        SA.DivisionId,
		SA.DivisionOrder,
		SA.DivisionName,
		SA.ClassId,
		SA.ClassName AS ClassName,

		CASE WHEN @rIsBasedOnSUId=0 THEN SA.Code Else ISNULL(SA.suid,'') END AS SUId,
		SA.Code
		
  FROM 		
		sStudent.vStudentAcademic SA
		--INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003
		--INNER JOIN sHostel.tRoomMaster RM ON  RM.Id=AR.RoomId 
	    --INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId 
		LEFT JOIN
		(SELECT SUM(ISNULL(DA.Amount,0)) AS TotalDeposit,DA.AcademicId,ISNull(DA.DepositHeadId,0) AS DepositHeadId FROM  sFee.tDepositAdd DA INNER JOIN sStudent.tAcademic A ON DA.AcademicId = A.Id  WHERE DA.DepositHeadId=@rDepositHeadId GROUP  BY DA.AcademicId,DA.DepositHeadId)D 
		ON D.AcademicId=SA.AcademicId
		LEFT JOIN 
		(SELECT SUM(ISNULL(AD.Amount,0)) AS TotalAdjustment,AD.AcademicId,ISNULL(AD.DepositHeadId,0) AS DepositHeadId FROM sFee.tDepositAdjustment AD INNER JOIN sStudent.tAcademic A ON AD.AcademicId = A.Id  WHERE AD.DepositHeadId=@rDepositHeadId GROUP BY AD.AcademicId,DepositHeadId)A 
		ON A.AcademicId=SA.AcademicId
		LEFT JOIN 
		(SELECT SUM(ISNULL(DR.RefundAmount,0)) AS TotalRefund,DR.AcademicId,ISNULL(DR.DepositHeadId,0) AS DepositHeadId FROM sFee.tDepositRefund DR INNER JOIN sStudent.tAcademic A ON DR.AcademicId = A.Id  WHERE   DR.DepositHeadId=@rDepositHeadId GROUP BY DR.AcademicId,DepositHeadId)R
		ON R.AcademicId=SA.AcademicId
		
    	--INNER JOIN  sFee.tDepositHeadMaster DHM ON DHM.Id = @rDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
  WHERE  
		(SA.OrgId=@rOrgId OR @rOrgId=0)
		
	AND(OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId=0)
	    --AND (DHM.Id=@rDepositHeadId)
	
		--AND (SA.BatchId=@rBatchId OR @rBatchId=0)
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((SA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
		--AND (AR.OrgGroupBatchId=@rOrgGroupBatchId)
		 
		
		--AND ((D.DepositDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		--AND ((D.DepositDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))
		
END
GO
PRINT N'Altering [sHostel].[pHostelDepositAddAdd]...';


GO
ALTER PROCEDURE [sHostel].[pHostelDepositAddAdd]
	 
	@rId bigint,
	@rHostelDepositHeadId int,
	@rStudentId bigint,
	@rAmount decimal(12,2),
	@rDepositDate date,
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(20),
	@rBankName nvarchar(200),
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rHostelId int,
	@rOrgGroupId smallint,
	@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lStudentId bigint,@lPriviousAmount decimal(12,2)=0
	DECLARE @lDepositAdd decimal(12,2)
	DECLARE @lAdjustmentAdd decimal(12,2)
	DECLARE @lRefundAdd decimal(12,2)
BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

  SELECT @lStudentId= StudentId FROM sStudent.vStudentAcademic Where AcademicId=@rStudentId AND OrgGroupBatchId=@rOrgGroupBatchId
  SELECT @lDepositAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
	    WHERE D.StudentId = @lStudentId
	    AND D.HostelDepositHeadId = @rHostelDepositHeadId   AND D.HostelId=@rHostelId AND D.OrgGroupBatchId=@rOrgGroupBatchId)
   SELECT @lAdjustmentAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdjustment D 
	    WHERE D.StudentId = @lStudentId
	     AND D.HostelDepositHeadId = @rHostelDepositHeadId   AND D.HostelId=@rHostelId AND D.OrgGroupBatchId=@rOrgGroupBatchId)
  SELECT @lRefundAdd = (SELECT ISNULL(SUM(R.RefundAmount),0) FROM sHostel.tHostelDepositRefund R 
	    WHERE R.StudentId = @lStudentId
	     AND R.HostelDepositHeadId = @rHostelDepositHeadId  AND R.HostelId=@rHostelId AND R.OrgGroupBatchId=@rOrgGroupBatchId)
	     
	    SET @lPriviousAmount=@lDepositAdd - @lAdjustmentAdd - @lRefundAdd
	-- AMOUNT VALIDATION
	--If EXISTS
	--(SELECT DB.BalanceAmount FROM sFee.tDepositBalance DB WHERE DB.DepositHeadId = @rDepositHeadId AND DB.ClassId=@lClassId AND BalanceAmount 
	-- < (SELECT  ISNULL(SUM(DA.Amount),0) + @rAmount AS TotalAmount FROM sFee.tDepositAdd DA 
	--	WHERE DepositHeadId = @rDepositHeadId AND StudentId=@lStudentId AND Id <> @rId)) 				
	--BEGIN
	--	SELECT -102 as Result
	--	RETURN
	--END 

 DECLARE @lNextNumber bigint 
 IF(@rId = 0)	    
 BEGIN  
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelDepositAdd', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sHostel.tHostelDepositAdd
		(
		Id,
		HostelDepositHeadId,
		StudentId,
		Amount,
		DepositDate,
		PayTypeId,
		ChequeNo,
		BankName,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		HostelId,
		OrgGroupBatchId,
		PreviousBalance
		)
	VALUES
		(
		@lNextNumber,
		@rHostelDepositHeadId,
		@lStudentId,
		@rAmount,
		@rDepositDate,
		@rPayTypeId,
		@rChequeNo,
		@rBankName,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rHostelId,
		@rOrgGroupBatchId,
		@lPriviousAmount
		) 
		SELECT @lNextNumber AS Result   
	END	
ELSE

    BEGIN 
    SET @lNextNumber = @rId
	    UPDATE sHostel.tHostelDepositAdd
	    SET
	    HostelDepositHeadId=@rHostelDepositHeadId,
	    StudentId=@lStudentId,
		Amount=@rAmount,
		DepositDate=@rDepositDate,
		PayTypeId=@rPayTypeId,
		ChequeNo=@rChequeNo,
		BankName=@rBankName,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate(),
	    HostelId=@rHostelId	 ,
	    OrgGroupBatchId=@rOrgGroupBatchId
	   
	    WHERE Id = @rId  AND HostelId=@rHostelId
	    SELECT @lNextNumber AS Result
	 END 
	  
	COMMIT TRANSACTION
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering [sHostel].[pHostelStudentGatePassNewGet]...';


GO


ALTER PROCEDURE [sHostel].[pHostelStudentGatePassNewGet]
          
           @rId int,
           @rOrgId int=0,
           @rHostelGatePassReasonId int=0,
           @rFromGatePassDate datetime='',
           @rToGatePassDate datetime='',
           @rEntryModeStatusId smallint=0,
           @rCode nvarchar(20)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0,
           @rOrgGroupBatchId int=0
AS
SET NOCOUNT ON
BEGIN
		SELECT
			HSGP.Id, 
			HSGP.Id AS HostelStudentGatePassId,
			vSA.Code,
			--vSA.FirstName+' '+vSA.LastName AS Name,
			VSA.Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			HSGP.StudentId,
			HSGP.RelationshipId,		
			RM.Title AS Relationship,
			HSGP.Relation,
			HSGP.VisitorName,
			HSGP.VisitorMobile,
			HSGP.HostelGatePassReasonId,
			HGRM.Title AS HostelGetPassReason,
			HSGP.Remark,
			--HSGP.VisitorPhoto	,
			
				
			--CASE  WHEN @rIsPrintView=1 THEN HSGP.VisitorPhoto		
			--ELSE ISNULL(HSGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			HSGP.GatePassDate,
			HSGP.GatePassInDate,
			(CASE  WHEN @rIsPrintView=1 THEN 
				HSGP.VisitorPhoto	
			ELSE ISNULL(HSGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
			 CONVERT(varchar(15),CAST(HSGP.GatePassTime AS TIME),100) As GatePassTime,
			  CONVERT(varchar(15),CAST(HSGP.GatePassInTime AS TIME),100) As GatePassInTime,
	
				--ISNULL(HSGP.GatePassTime,'') As GatePassTime,
			HSGP.EntryModeStatusId,
			HSGP.HostelId,
			SM.Title AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.StudentPhoto		
			ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS StudentPhoto,
			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			HSGP.OrgGroupBatchId,
			vSA.SUId,
			HM.Title As HostelName,
			HM.ReportOrgTitle AS ReportOrgTitle,
			HM.SmallAddress1 AS SmallAddress1,
			HM.SmallAddress2 AS SmallAddress2
			
		FROM 
		    sStudent.vStudentAcademic vSA
			INNER JOIN sHostel.tHostelStudentGatePass HSGP ON HSGP.StudentId = vSA.StudentId
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			LEFT JOIN sHostel.tHostelGatePassReasonMaster HGRM ON HGRM.Id=HSGP.HostelGatePassReasonId
			LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=HSGP.RelationshipId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=HSGP.EntryModeStatusId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
			LEFT JOIN sSecurity.tUser U	ON U.Id=HSGP.CreatedUserId
			LEFT JOIN  sHostel.tAssignRoom AR ON AR.SourceId=HSGP.StudentId AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		   INNER JOIN sHostel.tHostelMaster HM ON HM.Id = HSGP.HostelId
			
		WHERE 
			OM.OrgGroupId=@rOrgGroupId
			AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId) 
			AND (AR.SourceId=HSGP.StudentId) 
			AND (HSGP.OrgGroupBatchId=@rOrgGroupBatchId) 
		    AND ((HSGP.Id=@rId) OR (@rId=0))
			AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((HSGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((HSGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((HSGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			AND ((HSGP.HostelGatePassReasonId=@rHostelGatePassReasonId) OR (@rHostelGatePassReasonId=0))
			ORDER BY HSGP.GatePassDate,HSGP.GatePassTime DESC
END
GO
PRINT N'Altering [sHostel].[pImportHostelRoomAdd]...';


GO
ALTER PROCEDURE [sHostel].[pImportHostelRoomAdd]
	(	
		@rStrXml nvarchar(MAX) ,
	    @rOrgGroupBatchId int,
	    @rHosteld int
	    
		 
	)
AS

SET NOCOUNT ON

BEGIN
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT
			
 
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml
	 
	  
	UPDATE sHostel.tAssignRoom
	SET
		 RoomId = A1.RoomId 
	FROM
	(
		SELECT	
			 RoomId,
			 SourceId
			 			
			FROM OPENXML (@intDoc, '/Table/Import', 1)
			WITH
			(
				RoomId int '@RoomId',
				SourceId bigint '@SourceId' 
				
			))A1
	Where  A1.SourceId=sHostel.tAssignRoom.SourceId AND sHostel.tAssignRoom.OrgGroupBatchId=@rOrgGroupBatchId
	
	  	 
	INSERT INTO sHostel.tAssignRoom
	(
		 RoomId,
		 SourceTypeId,
		 SourceId,
		 OrgGroupBatchId
	)
	SELECT
		 RoomId,
		 2003,
		 SourceId,
		 @rOrgGroupBatchId
		
	FROM OPENXML (@intDoc, '/Table/Import', 1)
	WITH
	(
		RoomId int '@RoomId', --DepartmentId int '@DepartmentId',
		SourceId bigint '@SourceId' 
	)A1
	Where   A1.SourceId not in (Select SourceId from sHostel.tAssignRoom WHERE OrgGroupBatchId=@rOrgGroupBatchId)
	 
	 
	 	UPDATE sHostel.tHostelAdmission
	 	
	SET
		AllocateDate=getdate()
	FROM
	(
		SELECT	
			 
			 SourceId
			 			
			FROM OPENXML (@intDoc, '/Table/Import', 1)
			WITH
			(
				RoomId int '@RoomId',
				SourceId bigint '@SourceId' 
				
			))A1
	Where  A1.SourceId=sHostel.tHostelAdmission.SourceId AND sHostel.tHostelAdmission.OrgGroupBatchId=@rOrgGroupBatchId AND SourceTypeId=2003
	
	 INSERT INTO sHostel.tHostelAdmission
	(
		    Hosteld,
			SourceTypeId,
			SourceId,
			AllocateDate,
			OrgGroupBatchId,
			IsSelfPermissionToGoOut
	)
	SELECT
			 @rHosteld,
			 2003,
			 SourceId,
			 getdate(),
			 @rOrgGroupBatchId,
			 0
		
	FROM OPENXML (@intDoc, '/Table/Import', 1)
	WITH
	(
	    
		RoomId int '@RoomId', --DepartmentId int '@DepartmentId',
		SourceId bigint '@SourceId' 
	)A1
	Where   A1.SourceId not in (Select SourceId from sHostel.tHostelAdmission WHERE OrgGroupBatchId=@rOrgGroupBatchId AND SourceTypeId=2003)
	 
	 
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	
	 Select 1 As Result

END
GO
PRINT N'Altering [sHostel].[pRptHostelDepositAddReceiptGet]...';


GO

ALTER PROCEDURE [sHostel].[pRptHostelDepositAddReceiptGet]
          
		   @rId bigint,
		   @rOrgId int,          
           @rHostelDepositHeadId int,
           --@rBatchId int,
           @rOrgGroupId int,
           @rHostelId int,
           @rOrgGroupBatchId int,
           @rStudentId bigint=0,
           @rdate datetime=''
          -- @rIsBasedOnSUId bit = 0
AS
SET NOCOUNT ON 
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lCurrencyCode nvarchar(20) = ''
 
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = R.OrgGroupId  FROM sHostel.tHostelDepositHeadMaster R 
		INNER JOIN sSetup.tOrgGroupMaster OB ON R.OrgGroupId = OB.Id 
		WHERE R.Id = @rHostelDepositHeadId
		
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
	END
	ELSE
	BEGIN
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	END
	--SELECT  @lPriviousAmount =(SELECT (SELECT isnull(sum(DA.Amount),0) FROM  sHostel.tHostelDepositAdd DA WHERE DA.HostelDepositHeadId=@rHostelDepositHeadId AND DA.StudentId=@rStudentId AND DA.CreatedDateTime<@rdate  AND  DA.OrgGroupBatchId=@rOrgGroupBatchId ) -
 --      (SELECT isnull(sum(DA.Amount),0) FROM  sHostel.tHostelDepositAdjustment DA WHERE DA.HostelDepositHeadId=@rHostelDepositHeadId AND DA.StudentId=@rStudentId  AND DA.CreatedDateTime<@rdate   AND DA.OrgGroupBatchId=@rOrgGroupBatchId) -
 --      (SELECT isnull(sum(DA.RefundAmount),0) FROM  sHostel.tHostelDepositRefund DA WHERE DA.HostelDepositHeadId=@rHostelDepositHeadId AND DA.StudentId=@rStudentId AND DA.CreatedDateTime<@rdate  AND  DA.OrgGroupBatchId=@rOrgGroupBatchId ))

SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,
		PTM.Title AS PayType,
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.RollNo,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(DA.Amount,0.00),1,2,OM.OrgGroupId) AS ReceiptAmountInWords,
        vSA.BatchName,
        @lCurrencyCode AS CurrencyCode,
        HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
		--CASE WHEN @rIsBasedOnSUId=0 THEN  vSA.Code Else ISNULL(vSA.suid,'') END AS SUId
		ISNULL(vSA.suid,'')  AS SUId,
		DA.PreviousBalance As PriviousBalance
		
        
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tHostelDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=DA.PayTypeId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DA.HostelId 
  WHERE  
		--vSA.BatchId = @rBatchId 
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND (DA.Id=@rId)
	    AND (DA.HostelId=@rHostelId)
	    AND (DA.OrgGroupBatchId=@rOrgGroupBatchId)
	    AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
	    
		Order By DA.DepositDate
	
END
GO
PRINT N'Altering [sHostel].[prptHostelStudentGatePassbulkGet]...';


GO


ALTER PROCEDURE [sHostel].[prptHostelStudentGatePassbulkGet]
          
           @rbulkNo nvarchar(20),
           @rOrgGroupBatchId int,
           @rstudentid nvarchar(max)=''
AS
SET NOCOUNT ON
BEGIN
		SELECT
			HSGP.Id, 
			HSGP.Id AS HostelStudentGatePassId,
			vSA.Code,
			vSA.Name AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			HSGP.StudentId,
			HSGP.RelationshipId,		
			RM.Title AS Relationship,
			HSGP.Relation,
			 CASE WHEN HSGP.RelationshipId=2 Then SF.FatherName
			  WHEN HSGP.RelationshipId=3 Then SF.MotherName ELSE  HSGP.VisitorName   END AS VisitorName,
			 CASE WHEN HSGP.RelationshipId=2 Then SC.ParentContactNo
			     WHEN HSGP.RelationshipId=3 Then SC.ParentContactNo  ELSe  HSGP.VisitorMobile END AS VisitorMobile ,
			HSGP.HostelGatePassReasonId,
			HGRM.Title AS HostelGetPassReason,
			HSGP.Remark,
			--HSGP.VisitorPhoto	,
			
				
			--CASE  WHEN @rIsPrintView=1 THEN HSGP.VisitorPhoto		
			--ELSE ISNULL(HSGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			HSGP.GatePassDate,
			HSGP.GatePassInDate,
			 ISNULL(HSGP.VisitorPhoto, CONVERT(VARBINARY(MAX),''))  AS VisitorPhoto,
			 CONVERT(varchar(15),CAST(HSGP.GatePassTime AS TIME),100) As GatePassTime,
			  CONVERT(varchar(15),CAST(HSGP.GatePassInTime AS TIME),100) As GatePassInTime,
	
				--ISNULL(HSGP.GatePassTime,'') As GatePassTime,
			HSGP.EntryModeStatusId,
			HSGP.HostelId,
			SM.Title AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			  ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), ''))   AS StudentPhoto,
			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			HSGP.OrgGroupBatchId,
			vSA.SUId,
			HM.Title As HostelName,
			HM.ReportOrgTitle AS ReportOrgTitle,
			HM.SmallAddress1 AS SmallAddress1,
			HM.SmallAddress2 AS SmallAddress2
			
		FROM 
		    sStudent.vStudentAcademic vSA
			INNER JOIN sHostel.tHostelStudentGatePass HSGP ON HSGP.StudentId = vSA.StudentId AND VSA.OrgGroupBatchId=@rOrgGroupBatchId AND HSGP.OrgGroupBatchId=@rOrgGroupBatchId
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			LEFT JOIN sHostel.tHostelGatePassReasonMaster HGRM ON HGRM.Id=HSGP.HostelGatePassReasonId
			LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=HSGP.RelationshipId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=HSGP.EntryModeStatusId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
			LEFT JOIN sSecurity.tUser U	ON U.Id=HSGP.CreatedUserId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=HSGP.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=HSGP.StudentId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id = HSGP.HostelId
		WHERE 
			 
			 HSGP.BulkNumber=@rbulkNo
			 AND (ISNULL(vSA.StudentId,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rstudentid,',')) OR @rstudentid='') 
			 
END
GO
PRINT N'Altering [sHrm].[pEmployeeAttenanceviewGet]...';


GO
 

ALTER PROCEDURE [sHrm].[pEmployeeAttenanceviewGet]

		 @rBuilder1 nvarchar(max)=''
		,@rBuilder2 nvarchar(max)='' 
		,@rOrgId int
		,@rForMonth smallint
		,@rForYear smallint
		,@rBatchId int = 0
		,@rDepartmentId int = 0
		,@rDivisionId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lFirstDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		
BEGIN 
  
	SELECT  
			 @lFirstDate AS LastDate
			,PT.EmployeeId
			,Code
			,Name
			,ForYear
			,ForMonth
			,ForMonthInWord
			,(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount
			,ISNULL(TC.TCount,0) AS AttendanceCount
			,ISNULL(AC.ACount,0) As  AbsentCount
			,ISNULL(PC.PCount,0) As  PresentUpto
			,0 AS TotalPresent
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,1,@rBatchId,PT.EmployeeId,[1],@rOrgId) AS P1
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,2,@rBatchId,PT.EmployeeId,[2],@rOrgId) AS P2
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,3,@rBatchId,PT.EmployeeId,[3],@rOrgId) AS P3 
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,4,@rBatchId,PT.EmployeeId,[4],@rOrgId) AS P4
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,5,@rBatchId,PT.EmployeeId,[5],@rOrgId) AS P5
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,6,@rBatchId,PT.EmployeeId,[6],@rOrgId) AS P6
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,7,@rBatchId,PT.EmployeeId,[7],@rOrgId) AS P7
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,8,@rBatchId,PT.EmployeeId,[8],@rOrgId) AS P8
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,9,@rBatchId,PT.EmployeeId,[9],@rOrgId) AS P9
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,10,@rBatchId,PT.EmployeeId,[10],@rOrgId) AS P10
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,11,@rBatchId,PT.EmployeeId,[11],@rOrgId) AS P11
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,12,@rBatchId,PT.EmployeeId,[12],@rOrgId) AS P12
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,13,@rBatchId,PT.EmployeeId,[13],@rOrgId) AS P13
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,14,@rBatchId,PT.EmployeeId,[14],@rOrgId) AS P14
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,15,@rBatchId,PT.EmployeeId,[15],@rOrgId) AS P15
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,16,@rBatchId,PT.EmployeeId,[16],@rOrgId) AS P16
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,17,@rBatchId,PT.EmployeeId,[17],@rOrgId) AS P17
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,18,@rBatchId,PT.EmployeeId,[18],@rOrgId) AS P18
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,19,@rBatchId,PT.EmployeeId,[19],@rOrgId) AS P19
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,20,@rBatchId,PT.EmployeeId,[20],@rOrgId) AS P20
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,21,@rBatchId,PT.EmployeeId,[21],@rOrgId) AS P21
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,22,@rBatchId,PT.EmployeeId,[22],@rOrgId) AS P22
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,23,@rBatchId,PT.EmployeeId,[23],@rOrgId) AS P23
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,24,@rBatchId,PT.EmployeeId,[24],@rOrgId) AS P24
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,25,@rBatchId,PT.EmployeeId,[25],@rOrgId) AS P25
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,26,@rBatchId,PT.EmployeeId,[26],@rOrgId) AS P26
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,27,@rBatchId,PT.EmployeeId,[27],@rOrgId) AS P27
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,28,@rBatchId,PT.EmployeeId,[28],@rOrgId) AS P28
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,29,@rBatchId,PT.EmployeeId,[29],@rOrgId) AS P29
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,30,@rBatchId,PT.EmployeeId,[30],@rOrgId) AS P30
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,31,@rBatchId,PT.EmployeeId,[31],@rOrgId) AS P431
	FROM
		(
			SELECT   
				 Em.Code
				,Em.FirstName + ' ' + Em.LastName AS Name
				,Em.Id AS EmployeeId 
				,YEAR(ER.AttendanceDate) AS ForYear
				,MONTH(ER.AttendanceDate) AS ForMonth
				,DATENAME(MONTH, ER.AttendanceDate) AS ForMonthInWord
				,(CASE ER.IsPresent WHEN 1 THEN 'P' WHEN 0 THEN 'A' ELSE  ' ' END )AS  IsPresent		
				,DAY(ER.AttendanceDate) AS DayPart 
			FROM
				sHrm.tEmployeeMaster Em 
				INNER JOIN sHrm.tEmployeeAttendanceRegister ER ON ER.EmployeeId= EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
		    WHERE  
				((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((YEAR(ER.AttendanceDate)=@rForYear) OR (@rForYear= 0))
				AND ((MONTH(ER.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
				AND ((DM.Id=@rDepartmentId) OR (@rDepartmentId=0))
				AND (EJD.DateOfleaving >= (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
				OR ISNULL(EJD.DateOfleaving,'')='')				
				) AS SourceTable
			
			PIVOT
			(	
				MIN(IsPresent)
				FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
			) AS PT
			LEFT JOIN
			(
				SELECT EM.Id AS EmployeeId, COUNT(1) AS TCount 
				FROM sHrm.tEmployeeAttendanceRegister ER
				INNER JOIN sHrm.tEmployeeMaster EM ON ER.EmployeeId = EM.Id 
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.Employeeid = EM.Id
				INNER JOIN sSetup.tDepartmentMaster Deprt ON Deprt.Id= EJD.OrganizationDepartmentId
				WHERE 		
				((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((YEAR(ER.AttendanceDate)=@rForYear) OR (@rForYear= 0))
				AND ((MONTH(ER.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
				AND ((Deprt.Id=@rDepartmentId) OR (@rDepartmentId=0))
				GROUP BY Em.Id
			) TC ON TC.EmployeeId = PT.employeeid

			LEFT JOIN
			(
				SELECT EM.Id AS EmployeeId, COUNT(1) AS ACount 
				FROM sHrm.tEmployeeAttendanceRegister ER
				INNER JOIN sHrm.tEmployeeMaster EM ON ER.EmployeeId = EM.Id 
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.Employeeid = EM.Id
				INNER JOIN sSetup.tDepartmentMaster Deprt ON Deprt.Id= EJD.OrganizationDepartmentId
				WHERE
				ER.IsPresent = 0	 		
				AND (EM.StatusId = 7)
				AND ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((YEAR(ER.AttendanceDate)=@rForYear) OR (@rForYear= 0))
				AND ((MONTH(ER.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
				AND ((Deprt.Id=@rDepartmentId) OR (@rDepartmentId=0))		
				GROUP BY EM.Id
			) AC ON AC.EmployeeId = PT.EmployeeId
			LEFT JOIN
			(
				SELECT EM.Id AS Employeeid, COUNT(1) AS PCount  
				FROM sHrm.tEmployeeAttendanceRegister ER 
				INNER JOIN sHrm.tEmployeeMaster EM ON ER.EmployeeId = EM.Id 
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.Employeeid = EM.Id
				INNER JOIN sSetup.tDepartmentMaster Deprt ON Deprt.Id= EJD.Organizationdepartmentid
				WHERE  
				ER.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
				AND ER.IsPresent = 1	    		
				AND ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))	          
				AND ((Deprt.Id=@rDepartmentId) OR (@rDepartmentId=0))		
				GROUP BY EM.Id
			) PC ON PC.Employeeid = PT.EmployeeId

			ORDER BY Code
	  
END
GO
PRINT N'Altering [sHrm].[pEmployeePersonalDetailGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeePersonalDetailGet]
	
	@rOrgId smallint,
	@rEmployeeId [bigint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			EPD.UIDNumber,
			EPD.EmployeeId,			 
			EPD.DateOfBirth,
			EPD.GenderId,			
			ISNULL(EPD.ReligionId,0) AS ReligionId, 
			ISNULL(EPD.MaritalStatusId,0) AS MaritalStatusId, 
			EPD.IdentificationMark1,
			EPD.BloodGroupId, 
			ISNULL(EPD.Qualification,'') AS Qualification,
			EPD.UpdatedUserId,
			EPD.UpdatedDateTime,
			ISNULL(EPD.FamilyCast,'') AS FamilyCast,
			ISNULL(EPD.CastCategoryId,0) AS CastCategoryId,
			AdhaarNumber
	FROM 
			sHrm.tEmployeePersonalDetail EPD 
	WHERE 
			((EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND EPD.OrgId = @rOrgId
END
GO
PRINT N'Altering [sHrm].[pEmployeePersonalDetailModify]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeePersonalDetailModify]
	 
	@rEmployeeId [bigint],
	@rUIDNumber [nvarchar](50),
	@rDateOfBirth	date,
	@rGenderId	tinyint,
	@rReligionId	int,
	@rMaritalStatusId	tinyint,
	@rIdentificationMark1	nvarchar(100),
	@rBloodGroupId	tinyint,
	@rQualification	nvarchar(150),
	@rUpdatedUserId [bigint],
	@rFamilyCast nvarchar(150)='',
	@rCastCategoryId int=NULL,
	@rAdhaarNumber nvarchar(20)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		IF (@rReligionId <= 0)
			SET @rReligionId = NULL			
		IF (@rCastCategoryId <= 0)
			SET @rCastCategoryId = NULL		
  		IF (@rMaritalStatusId <= 0)
			SET @rMaritalStatusId = NULL	
	  	IF (@rBloodGroupId <= 0 OR @rBloodGroupId Is null)
			SET @rBloodGroupId = 9			
	
	UPDATE sHrm.tEmployeePersonalDetail
		SET 
				UIDNumber = @rUIDNumber,
				DateOfBirth	=	@rDateOfBirth,
				GenderId	=	@rGenderId,
				ReligionId	=	@rReligionId,
				MaritalStatusId	=	@rMaritalStatusId,
				IdentificationMark1	=	@rIdentificationMark1,		 
				BloodGroupId	=	@rBloodGroupId,
				Qualification	=	@rQualification,
				UpdatedUserId = @rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				FamilyCast = @rFamilyCast,
				CastCategoryId = @rCastCategoryId,
				AdhaarNumber =@rAdhaarNumber
	    WHERE 
				EmployeeId = @rEmployeeId
	       
	  SELECT 1 AS RESULT
END
GO
PRINT N'Altering [sHrm].[pImportEmployee]...';


GO
ALTER PROCEDURE [sHrm].[pImportEmployee]
	
	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
    
			@intDoc INT,
			@lCode nvarchar(20),
			@lShortName nvarchar(50),
			@lFirstName Nvarchar(100),
			@lMiddleName Nvarchar(100),
			@lLastName Nvarchar(100),
			@lGenderId int = 0,
			@lGender nvarchar(10),
			@lEmployeeTypeId int = 0,
			@lEmployeeType nvarchar(100),
			@lEmployeeGroupId int,
			@lEmployeeGroup nvarchar(100),
			@lEmployeeGradeId int,
			@lEmployeeGrade nvarchar(100),
			@lDepartmentId int,
			@lDepartment nvarchar(100),
			@lDesignationId int,
			@lDesignation nvarchar(100),
			@lQualification nvarchar(150),
			@lDOB DATETIME,
			@lDOJ DATETIME,
			@lReligionId int,
			@lReligion nvarchar(100),
			
			@lCastCategoryId int,
			@lCastCategory nvarchar(50),
				
			@lCompanyPhoneNo Nvarchar(50),
			@lExtentionNo Nvarchar(10),
			@lCompanyEmailId Nvarchar(100),
			@lPersonalEmailId Nvarchar(100),
			@lMobileNo Nvarchar(20),
			@lPresentStreetOne nvarchar(50),
			@lPresentStreetTwo nvarchar(50),
			@lPresentStreetThree nvarchar(50),
			@lPresentCity nvarchar(50),
			@lPresentZipCode nvarchar(20),
			@lPresentState nvarchar(50),
			@lPresentCountry nvarchar(50),
			@lPresentContactNo nvarchar(20),
			@lFamilyCast nvarchar(150),
			@lAccountNumber nvarchar(150),
			@lBankName nvarchar(150),
			@lBranch nvarchar(150),
			@lEPFNumber nvarchar(150),
			@lPanNumber nvarchar(150),
			@OutDesignationId int,
			@lAdhaarNumber nvarchar(20)
			 
			
DECLARE @OutEmployeeId bigint		
			
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		Code nvarchar(20),
		ShortName nvarchar(50),
		FirstName Nvarchar(100),
		MiddleName Nvarchar(100) null,
		LastName Nvarchar(100),
		GenderId int null,
		Gender nvarchar(10),
		EmployeeTypeId int null,
		EmployeeType nvarchar(100),
		EmployeeGroupId int null,
		EmployeeGroup nvarchar(100),
		EmployeeGradeId int null,
		EmployeeGrade nvarchar(100),
		DepartmentId int null,
		Department nvarchar(100),
		DesignationId int null,
		Designation nvarchar(100),
		Qualification nvarchar(150),	 
		DOB date,
		DOJ date,
		ReligionId int,
		Religion nvarchar(100),
		CastCategoryId int,
		CastCategory nvarchar(50),
		CompanyPhoneNo nvarchar(50) null,
		ExtentionNo nvarchar(10) null,
		CompanyEmailId nvarchar(100) null,
		PersonalEmailId nvarchar(100) null,
		MobileNo nvarchar(20) null,
		PresentStreetOne nvarchar(50),
		PresentStreetTwo nvarchar(50),
		PresentStreetThree nvarchar(50),
		PresentCity nvarchar(50),
		PresentZipCode nvarchar(20),
		PresentState nvarchar(50),
		PresentCountry nvarchar(50),
		PresentContactNo nvarchar(20),
		FamilyCast nvarchar(150),
		AccountNumber nvarchar(150),
		BankName nvarchar(150),
		Branch nvarchar(150),
		EPFNumber nvarchar(150),
		PanNumber nvarchar(150),
		CreatedUserId bigint null,
		AdhaarNumber nvarchar(20)
	)
		
	INSERT INTO #tTable
	(
		Code,
		ShortName,
		FirstName,
		MiddleName,
		LastName,
		GenderId,
		Gender,
		EmployeeTypeId,
		EmployeeType,
		EmployeeGroupId,
		EmployeeGroup,
		EmployeeGradeId,
		EmployeeGrade,
		DepartmentId,
		Department,
		DesignationId,
		Designation,
		Qualification,	 
		DOB,
		DOJ,
		ReligionId,
		Religion,
		CastCategoryId,
		CastCategory,
		CompanyPhoneNo,
		ExtentionNo,
		CompanyEmailId,
		PersonalEmailId,
		MobileNo,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		FamilyCast,
		AccountNumber,
		BankName,
		Branch,
		EPFNumber,
		PanNumber,		
		CreatedUserId,
		AdhaarNumber
	)
	SELECT
		Code,
		ShortName,
		FirstName,
		MiddleName,
		LastName,
		0,
		Gender,
		0,
		EmployeeType,
		0,
		EmployeeGroup,
		0,
		EmployeeGrade,
		0,
		Department,
		0,
		Designation,
		Qualification,	 
		DOB,
		DOJ,
		0,
		Religion,
		0,
		CastCategory,
		CompanyPhoneNo,
		ExtentionNo,
		CompanyEmailId,
		PersonalEmailId,
		MobileNo,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		FamilyCast,
		AccountNumber,
		BankName,
		Branch,
		EPFNumber,
		PanNumber,	
		CreatedUserId,
		AdhaarNumber
		
	FROM OPENXML (@intDoc, '/Table/ImportEmployee', 1)
	WITH
	( 
		Code nvarchar(20) '@Code',
		ShortName nvarchar(50) '@ShortName',
		FirstName Nvarchar(100) '@FirstName',
		MiddleName Nvarchar(100) '@MiddleName',
		LastName Nvarchar(100) '@LastName',  			
		Gender nvarchar(10) '@Gender', 			
		EmployeeType nvarchar(100) '@EmployeeType',		
		EmployeeGroup nvarchar(100) '@EmployeeGroup',
		EmployeeGrade nvarchar(100) '@EmployeeGrade',	
		Department nvarchar(100) '@Department', 			
		Designation nvarchar(100) '@Designation',	 		
		Qualification nvarchar(150) '@Qualification',	 			
		DOB nvarchar(15) '@DOB', 			
		DOJ nvarchar(15) '@DOJ',	 			
		Religion nvarchar(100) '@Religion',
		CastCategory nvarchar(50) '@CastCategory',
		CompanyPhoneNo nvarchar(50) '@CompanyPhoneNo',
		ExtentionNo nvarchar(10) '@ExtentionNo', 	
		CompanyEmailId nvarchar(100) '@CompanyEmailId',
		PersonalEmailId nvarchar(100) '@PersonalEmailId',
		MobileNo nvarchar(20) '@MobileNo',
		PresentStreetOne nvarchar(50) '@PresentStreetOne',
		PresentStreetTwo nvarchar(50) '@PresentStreetTwo',
		PresentStreetThree nvarchar(50) '@PresentStreetThree',
		PresentCity nvarchar(50) '@PresentCity',
		PresentZipCode nvarchar(20) '@PresentZipCode',
		PresentState nvarchar(50) '@PresentState',
		PresentCountry nvarchar(50) '@PresentCountry',
		PresentContactNo nvarchar(20) '@PresentContactNo',		
		CreatedUserId bigint '@CreatedUserId',
		FamilyCast nvarchar(150) '@FamilyCast',
		AccountNumber nvarchar(150) '@AccountNumber',
		BankName nvarchar(150) '@BankName',
		Branch nvarchar(150) '@Branch',
		EPFNumber nvarchar(150) '@EPFNumber',
		PanNumber nvarchar(150) '@PanNumber',
		AdhaarNumber nvarchar(20) '@AdhaarNumber'
	)
	
 
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 

BEGIN
		SET	@lCode = ''	
		SET @lShortName = ''
		SET @lFirstName = ''
		SET @lMiddleName = ''
		SET @lLastName = ''	
		SET	@lGenderId = 0
		SET	@lGender = ''
		SET	@lEmployeeTypeId = 0
		SET	@lEmployeeType = ''
		SET	@lEmployeeGroupId = null
		SET	@lEmployeeGroup = ''
		SET	@lEmployeeGradeId = null
		SET	@lEmployeeGrade = ''
		SET	@lDepartmentId = null
		SET	@lDesignationId = null
		SET	@lDepartment = ''
		SET	@lDesignation = ''
		SET @lQualification = ''	
		SET	@lDOB = null
		SET	@lDOJ = null
		SET @lReligionId = null
		SET @lReligion = ''
		SET @lCastCategoryId = NULL
		SET @lCastCategory =''
		SET	@lCompanyPhoneNo = null
		SET	@lExtentionNo = null
		SET	@lCompanyEmailId = null
		SET	@lPersonalEmailId = null
		SET	@lMobileNo = null
		SET @OutEmployeeId = null
		SET @lPresentStreetOne = ''
		SET @lPresentStreetTwo = ''
		SET @lPresentStreetThree = ''
		SET @lPresentCity = ''
		SET @lPresentZipCode = ''
		SET @lPresentState = ''
		SET @lPresentCountry = ''
		SET @lPresentContactNo = ''
		SET	@lFamilyCast = ''
		SET	@lAccountNumber = ''
		SET	@lBankName = ''
		SET	@lBranch = ''
		SET	@lEPFNumber = ''
		SET	@lPanNumber = ''
		Set @lAdhaarNumber=''
SELECT		
		@lCode = Code,
		@lShortName = ShortName,
		@lFirstName = FirstName,
		@lMiddleName = MiddleName,
		@lLastName = LastName,	
		@lGender = Gender,
		@lEmployeeType = EmployeeType,	
	    @lEmployeeGroup = EmployeeGroup,
	    @lEmployeeGrade = EmployeeGrade,
		@lDepartment = Department,
		@lDesignation= Designation,	
		@lQualification = Qualification,	
		@lDOB = CASE			
		WHEN DOB = '' THEN  '01/01/1990'
		ELSE DOB  
		--CONVERT(datetime, DOB, 103)
		END,		
		@lDOJ = CASE	
		WHEN DOJ = '' THEN  GETDATE()
		ELSE DOJ 
		END,			
		--@lDOB = convert(datetime, DOB, 103),
		--@lDOJ = convert(datetime, DOJ, 103),
		@lReligion = Religion,
		@lCastCategory = CastCategory,
	    @lCompanyPhoneNo = CompanyPhoneNo,
	    @lExtentionNo = ExtentionNo,
	    @lCompanyEmailId = CompanyEmailId,
		@lPersonalEmailId = PersonalEmailId,
		@lMobileNo = MobileNo,
		@lPresentStreetOne = PresentStreetOne,
		@lPresentStreetTwo = PresentStreetTwo,
		@lPresentStreetThree = PresentStreetThree,
		@lPresentCountry = PresentCountry,
		@lPresentState = PresentState,
		@lPresentCity = PresentCity,
		@lPresentZipCode = PresentZipCode,
		@lPresentContactNo = PresentContactNo,
		@lFamilyCast = FamilyCast,
		@lAccountNumber = AccountNumber,
		@lBankName = BankName,
		@lBranch = Branch,
		@lEPFNumber = EPFNumber,
		@lPanNumber = PanNumber,
		@lAdhaarNumber =AdhaarNumber
											 	 
FROM #tTable WHERE Id = @lCount  

--select * from #tTable

	SELECT	@lGenderId = ID FROM sCommon.tGenderMaster WHERE Title = @lGender
	SELECT	@lEmployeeTypeId = ID FROM sHrm.tEmployeeTypeMaster WHERE Title = @lEmployeeType AND OrgId = @rOrgId
	SELECT	@lEmployeeGroupId  = ID FROM sHrm.tEmployeeGroupMaster WHERE Title = @lEmployeeGroup
	SELECT	@lEmployeeGradeId  = ID FROM sHrm.tEmployeeGradeMaster WHERE Title = @lEmployeeGrade AND OrgId = @rOrgId
	SELECT	@lDepartmentId  = ID FROM sSetup.tDepartmentMaster WHERE Title = @lDepartment AND OrgId = @rOrgId
	SELECT	@lDesignationId  = ID FROM sHrm.tEmployeeDesignationMaster WHERE Title = @lDesignation AND OrgId = @rOrgId
	SELECT	@lReligionId  = ID FROM sCommon.tReligionMaster WHERE Title = @lReligion AND OrgGroupId = @rOrgGroupId
	SELECT	@lCastCategoryId  = ID FROM sCommon.tCastCategoryMaster WHERE Title = @lCastCategory AND OrgGroupId = @rOrgGroupId
	
	IF(@lGenderId IS NULL)
		SET @lGenderId = 0
	IF(@lEmployeeGroupId IS NULL)
		SET @lEmployeeGroupId = 0
	IF(@lEmployeeGradeId IS NULL)
		SET @lEmployeeGradeId = 0
	
 BEGIN TRANSACTION
    --Default Group Id = 1
--IF 	@lDepartmentId IS NULL  AND @lDepartment != ''
--BEGIN
--DECLARE @1DepartmentGroupId  int 
-- SET @1DepartmentGroupId = sCommon.fGetIntIdForOrg(1,@rOrgId) 
-- EXEC [sCommon].[pOrganizationDepartmentMasterAdd] @rOrgId,@lDepartment,@lDepartment,0,@rUserId,@OutDepartmentId OUTPUT
--END
--ELSE
--SET @OutDepartmentId = @lDepartmentId

--IF 	@lEmployeeGradeId IS NULL  AND @lEmployeeGrade != ''
--BEGIN
--DECLARE @1EmployeeGradeGroupId  int 
-- EXEC [sHrm].[pEmployeeGradeMasterAdd] @rOrgId,@lEmployeeGrade,@lEmployeeGrade,0,@rUserId,@OutEmployeeGradeId OUTPUT
--END
--ELSE
--SET @OutEmployeeGradeId = @lEmployeeGradeId

IF 	@lDesignationId IS NULL  AND @lDesignation != ''
BEGIN
 EXEC [sHrm].[pEmployeeDesignationMasterAdd] @rOrgId,@lDesignation,@lDesignation,0,@rUserId,@OutDesignationId = @OutDesignationId OUTPUT
END
ELSE
SET @OutDesignationId = @lDesignationId

--UPDATE #tTable SET
--		GenderId = @lGenderId ,
--		EmpTypeId = @lEmpTypeId,
--		DepartmentId = @OutDepartmentId,
--		DesignationId = @lDesignationId,
--		ContractorId = @OutContractorId,
--		BloodGroupId = @lBloodGroupId WHERE Id = @lCount
 	
	
 
EXEC [sHrm].[pEmployeeMasterAdd] @rOrgId,@lCode,@lFirstName,@lMiddleName,@lLastName,@lEmployeeTypeId,
@lDepartmentId,@lDOB,@lDOJ,@lGenderId,@lReligionId,7,0,@rUserId,@OutEmployeeId OUTPUT,
@lDesignationId,NULL,@lQualification,@lEmployeeGradeId,@lEmployeeGroupId,@lShortName,@lReligionId
 
EXEC [sHrm].[pEmployeeCommunicationsAdd] @OutEmployeeId,@lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetThree,
@lPresentCountry,@lPresentState,@lPresentCity,@lPresentZipCode,@lPresentContactNo,NULL,Null,Null,NULL,NULL,NULL,NULL,Null,
Null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,@lCompanyPhoneNo,@lExtentionNo,@lCompanyEmailId,@lPersonalEmailId,@lMobileNo,@rUserId
		
EXEC [sHrm].[pEmployeeStatutoryDetailAdd] @OutEmployeeId,@lAccountNumber,@lBankName,@lBranch,@lEPFNumber,@lPanNumber,
 0,NULL,NULL,0,0,NULL,NULL,NULL,@rUserId,NULL,0,NULL,NULL					

		SET @lCount = @lCount - 1	
		COMMIT TRANSACTION	
END
		SELECT 1 Result		
	END TRY
	BEGIN CATCH
	
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END
GO
PRINT N'Altering [sIp].[pWeightedAverageCostLogAdd_New]...';


GO
ALTER PROCEDURE [sIp].[pWeightedAverageCostLogAdd_New]
	@rOrgGroupId [int],
	@rSourceTypeId [smallint],
	@rSourceId [bigint],
	@rItemSourceTypeId [smallint],
	@rItemSourceId [bigint],
	@rQuantity [decimal](12, 2),
	@rValue [decimal](22, 6),
	@rIsReceipt [bit],
	--@rClosingQuantity [decimal](12, 2),
	--@rClosingValue [decimal](22, 6),
	@rWeightedAverageCost [decimal](22, 6)=0,
	@rCreatedUserId [bigint],
	@rStoreLocationId [int]  ,
	@rStoreLocationClosingQuantity [decimal](12, 2) = 0,
	@rPhysicalQuantity decimal(12,2)=0,
	@rItemBatchId int = 0,
	@rItemName nvarchar(200) = '',
	@rLocationId [int],
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

 

BEGIN

 --BEGIN TRY	
	       --BEGIN TRANSACTION
	       
	DECLARE @lOldClosingQuantity [decimal](12, 2) = 0
	DECLARE @lOldClosingValue [decimal](12, 2) = 0
	DECLARE @lOldWeightedAverageCost [decimal](12, 2) = 0
	DECLARE @lNewClosingQuantity [decimal](12, 2) = 0
	DECLARE @lNewClosingValue [decimal](12, 2) = 0
	DECLARE @lNewWeightedAverageCost [decimal](12, 2)= 0	
	DECLARE @lStockBatchQuantity [decimal](12, 2) = 0
	       
	SELECT @lStockBatchQuantity = SB.AvailableQuantity FROM sProcurement.tStockBatch SB  
	WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId AND SB.StoreLocationId =@rStoreLocationId       
	       
	if @rSourceTypeId=50 -- Stock Adjustment
	BEGIN 
		SET @lNewClosingQuantity = ISNULL(@rPhysicalQuantity,0) 
		SET @lNewClosingValue =   ISNULL(@rPhysicalQuantity,0) * @rWeightedAverageCost
		SET @lNewWeightedAverageCost = @rWeightedAverageCost
	END
	ELSE
	BEGIN
		SELECT TOP 1 @lOldClosingQuantity = ClosingQuantity,@lOldClosingValue = ClosingValue,
		@lOldWeightedAverageCost = WeightedAverageCost FROM sIp.tWeightedAverageCostLog
		WHERE ItemSourceId = @rItemSourceId AND StoreLocationId = @rStoreLocationId ORDER BY ID Desc	 
		IF (@rIsReceipt = 1)
		BEGIN
			SET @lNewClosingQuantity = ISNULL(@lOldClosingQuantity,0) + @rQuantity
			SET @lNewClosingValue =   ISNULL(@lOldClosingValue,0) + @rValue
			SET @lNewWeightedAverageCost = @lNewClosingValue / @lNewClosingQuantity
			SET @lStockBatchQuantity = @lStockBatchQuantity + @rQuantity
		END
		ELSE
		BEGIN
			SET @lNewClosingQuantity = ISNULL(@lOldClosingQuantity,0) - @rQuantity
			SET @lNewClosingValue =   ISNULL(@lOldClosingValue,0) - @rValue
			SET @lNewWeightedAverageCost = @lOldWeightedAverageCost		
			SET @lStockBatchQuantity = @lStockBatchQuantity - @rQuantity
		END
	END      
	DECLARE @lNextNumber BIGINT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sIp.tWeightedAverageCostLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	IF NOT EXISTS (SELECT 1 FROM sIp.tWeightedAverageCostLog WHERE SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId
	AND StoreLocationID = @rStoreLocationId)
	BEGIN
		INSERT INTO sIp.tWeightedAverageCostLog
		(
			 SourceTypeId,SourceId,ItemSourceTypeId,ItemSourceId,Quantity,Value,IsReceipt,
			ClosingQuantity,ClosingValue,WeightedAverageCost,CreatedUserId,CreatedDateTime,StoreLocationId,
			StoreLocationClosingQuantity,OrgGroupId,LocationId
		)
		VALUES
		(
			@rSourceTypeId,@rSourceId,@rItemSourceTypeId,@rItemSourceId,@rQuantity,@rValue,@rIsReceipt,
			@lNewClosingQuantity,@lNewClosingValue,@lNewWeightedAverageCost,@rCreatedUserId,sCommon.fGetDate(),
			@rStoreLocationId,@rStoreLocationClosingQuantity,@rOrgGroupId,@rLocationId
		)
	END
	IF (@rSourceTypeId = 46 AND @rItemSourceTypeId = 34) -- GoodReceiptNotBatch
	BEGIN
		UPDATE sip.tStockItemPlanning  
		SET WeightedAverageCost = @lNewWeightedAverageCost 
		WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
	END
	IF (@rSourceTypeId = 1010 AND @rItemSourceTypeId = 34) -- Stock Inward
	BEGIN 
		Update SB Set SB.AvailableQuantity = SB.AvailableQuantity + @rQuantity,SB.ItemRate = @rValue
		from sProcurement.tStockBatch SB WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId
		AND SB.StoreLocationId =@rStoreLocationId
		 
		UPDATE sip.tStockItemPlanning  
		SET WeightedAverageCost = @lNewWeightedAverageCost 
		WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
		--select  SB.AvailableQuantity from sProcurement.tStockBatch SB WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId
		--AND SB.StoreLocationId =@rStoreLocationId
	END
	IF (@rSourceTypeId = 51 OR @rSourceTypeId = 48 ) -- Stock Issue / dispense
	BEGIN
		Update SB Set SB.AvailableQuantity = SB.AvailableQuantity - @rQuantity
		from sProcurement.tStockBatch SB WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId
		AND SB.StoreLocationId =@rStoreLocationId		
	END
	if(@rSourceTypeId = 1013) -- Stock Inward Return
	BEGIN
		Update SB Set SB.AvailableQuantity = SB.AvailableQuantity - @rQuantity from sProcurement.tStockBatch SB
		Where SB.Id=@rItemBatchId AND SB.StockItemId= @rItemSourceId And SB.StorelocationID=@rStoreLocationId
	END	 
		IF(@rSourceTypeId = 1012) -- Stock Issue Return
	BEGIN
		Update SB Set SB.AvailableQuantity = SB.AvailableQuantity + @rQuantity from sProcurement.tStockBatch SB
		Where SB.Id=@rItemBatchId AND SB.StockItemId= @rItemSourceId And SB.StorelocationID=@rStoreLocationId
	END	 
	
	  
	 
	IF NOT EXISTS (SELECT 1 FROM sIp.tWeightedAverageCostLog WHERE SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId
	AND StoreLocationID = @rStoreLocationId)
	BEGIN
	 
	if(@rSourceTypeId != 2028)
	BEGIN
	 
		INSERT INTO sIp.tWeightedAverageCostLog
		(
			SourceTypeId,SourceId,ItemSourceTypeId,ItemSourceId,Quantity,Value,IsReceipt,
			ClosingQuantity,ClosingValue,WeightedAverageCost,CreatedUserId,CreatedDateTime,StoreLocationId,
			StoreLocationClosingQuantity,OrgGroupId,LocationId
		)
		VALUES
		(
			@rSourceTypeId,@rSourceId,@rItemSourceTypeId,@rItemSourceId,@rQuantity,@rValue,@rIsReceipt,
			@lNewClosingQuantity,@lNewClosingValue,@lNewWeightedAverageCost,@rCreatedUserId,sCommon.fGetDate(),
			@rStoreLocationId,@rStoreLocationClosingQuantity,@rOrgGroupId,@rLocationId
		)
	END
	else
		BEGIN
	 
	 set @lNewWeightedAverageCost = isnull(@rValue,0)
	 SET @lNewClosingValue =   (isnull(@rQuantity,0) * isnull(@rValue,0))
	 INSERT INTO sIp.tWeightedAverageCostLog
		(
			SourceTypeId,SourceId,ItemSourceTypeId,ItemSourceId,Quantity,Value,IsReceipt,
			ClosingQuantity,ClosingValue,WeightedAverageCost,CreatedUserId,CreatedDateTime,StoreLocationId,
			StoreLocationClosingQuantity,OrgGroupId,LocationId
		)
		VALUES
		(
			@rSourceTypeId,@rSourceId,@rItemSourceTypeId,@rItemSourceId,@rQuantity,@rValue,@rIsReceipt,
			@rQuantity,@lNewClosingValue,@lNewWeightedAverageCost,@rCreatedUserId,sCommon.fGetDate(),
			@rStoreLocationId,@rStoreLocationClosingQuantity,@rOrgGroupId,@rLocationId
		)
		END
	END       
	       
 IF (@rSourceTypeId = 2028 AND @rItemSourceTypeId = 34) -- Stock Reset
	BEGIN 
		
		Update SB Set SB.AvailableQuantity = @rQuantity ,SB.ItemRate = @rValue
		from sProcurement.tStockBatch SB WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId
		AND SB.StoreLocationId =@rStoreLocationId
		
		UPDATE sip.tStockItemPlanning  
		SET WeightedAverageCost = @rValue 
		WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId		
		
	END
	       
	--IF EXISTS (SELECT 1 FROM sIp.tWeightedAverageCostLog WHERE ItemSourceId = @rItemSourceId AND StoreLocationId = @rStoreLocationId)
	--       BEGIN
	--	IF (@rClosingQuantity < 0)
	--	BEGIN
	--		--RAISERROR('-101', 15, 106)
	--		Select -102 AS RESULT
	--		RETURN
	--	END
	--	END
	--DECLARE @lNextNumber BIGINT
	--DECLARE @lLocationId INT
	----EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sIp.tWeightedAverageCostLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	----Added for Issue HIMS - 6338
	-- EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] 1001, 'sIp.tWeightedAverageCostLog',@lNextNumber = @lNextNumber output
	
	--IF @rStoreLocationId = 0 
	--BEGIN
	--	SET @rStoreLocationId = 1
	--END
	
	----SELECT @lLocationId = LocationId FROM sIp.tStoreLocationMaster WHERE ID = @rStoreLocationId
	-- SET @lLocationId = 0
 --IF NOT EXISTS (SELECT 1 FROM sIp.tWeightedAverageCostLog WHERE SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId AND StoreLocationID = @rStoreLocationId)
 -- BEGIN	 
	---- END of addition
	--INSERT INTO sIp.tWeightedAverageCostLog
	--	(
	--		Id, 
	--		SourceTypeId, 
	--		SourceId, 
	--		ItemSourceTypeId, 
	--		ItemSourceId, 
	--		Quantity, 
	--		Value, 
	--		IsReceipt, 
	--		ClosingQuantity, 
	--		ClosingValue, 
	--		WeightedAverageCost, 
	--		CreatedUserId, 
	--		CreatedDateTime, 
	--		StoreLocationId, 
	--		StoreLocationClosingQuantity,
	--		OrgGroupId,
	--		LocationId
	--	)
	--VALUES
	--	(
	--		@lNextNumber,
	--		@rSourceTypeId, 
	--		@rSourceId, 
	--		@rItemSourceTypeId, 
	--		@rItemSourceId, 
	--		@rQuantity, 
	--		@rValue, 
	--		@rIsReceipt, 
	--		@rClosingQuantity, 
	--		@rClosingValue, 
	--		@rWeightedAverageCost, 
	--		@rCreatedUserId, 
	--		sCommon.fGetDate(),
	--		@rStoreLocationId, 
	--		@rStoreLocationClosingQuantity,
	--		@rOrgId,
	--		@lLocationId
			
	--	)
	--END
		
	--	IF (@rSourceTypeId = 46 AND @rItemSourceTypeId = 34)
	--	BEGIN
	--		UPDATE sip.tStockItemPlanning  
	--		SET WeightedAverageCost = @rWeightedAverageCost 
	--		WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
	--	END
		
	--	IF (@rSourceTypeId = 1010 AND @rItemSourceTypeId = 34)
	--	BEGIN
	--		UPDATE sip.tStockItemPlanning  
	--		SET WeightedAverageCost = @rWeightedAverageCost 
	--		WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
	--	END
  
		-- COMMIT TRANSACTION
  --      END TRY
         
  --      BEGIN CATCH
		--ROLLBACK TRANSACTION
		--SELECT -1 AS RESULT
	 --   END CATCH	
END




/****** Object:  StoredProcedure [sIp].[pStockItemMasterGet]    Script Date: 07/09/2013 16:14:40 ******/
SET ANSI_NULLS ON
GO
PRINT N'Altering [sLibrary].[pLibraryAttendanceDivisionWIseoutTimeAdd]...';


GO


ALTER PROCEDURE [sLibrary].[pLibraryAttendanceDivisionWIseoutTimeAdd]

	 
	@rLibraryId int,
	 
	@rDetail nvarchar(max),
	 
	@rAttendanceDate date,
  
	@rOutTime time(7),
	@rRemark nvarchar(200),
	@rOrgGroupBatchId int
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 BEGIN TRANSACTION	
	SET @rDetail=REPLACE(@rDetail,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rDetail	
		Update 
			sLibrary.tLibraryAttendance 
		set OutTime =@rOutTime,AttendanceDate=@rAttendanceDate,
			Remark=A.Remark
		From 
		(
		Select  SourceId ,Remark
			FROM OPENXML (@intDoc, '/Table/RowData', 1)
			WITH
			( 
				SourceId bigint '@SourceId',
				Remark nvarchar(200) '@Remark'
			))A
			Where sLibrary.tLibraryAttendance.SourceId=A.SourceId 
			And sLibrary.tLibraryAttendance.LibraryId=@rLibraryId
			 And OrgGroupBatchId=@rOrgGroupBatchId AND SourceTypeId=2003
	EXEC sp_xml_removedocument @intDoc
		COMMIT TRANSACTION
		
	 
		
END
GO
PRINT N'Altering [sProcurement].[pStockInwardGet]...';


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

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

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


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


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

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


GO

ALTER PROCEDURE [sSecurity].[pEmployeePasswordAdd]
	
	@rId bigint,
	@rEmployeeId bigint,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rName nvarchar(100),
	@rEmailId nvarchar(100),
	@rMobileNo nvarchar(20),
	@rUserName nvarchar(100),
	@rLoginPassword nvarchar(100),
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rIsFullUpdate bit,
	@rRoleId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		
		
		
		IF(@rId = 0)	
		BEGIN
			IF(@rEmployeeId <> 0)
			BEGIN
				IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceTypeId = 95 AND SourceId = @rEmployeeId AND OrgId=@rOrgId)
				BEGIN
					SELECT -101 AS UserId
					RETURN
				END
			END
			
			IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rUserName AND OrgId = @rOrgId)
			BEGIN
				SELECT -101 AS UserId
				RETURN
			END
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rUserName AND OrgId = @rOrgId AND Id<>@rId)
			BEGIN
				SELECT -101 AS UserId
				RETURN
			END
		END
	 DECLARE @lCurrentDateTime DATETIME
	 EXECUTE @lCurrentDateTime = sCommon.fGetDate
	 IF(@rIsFullUpdate=0)
	 BEGIN
	 UPDATE sHrm.tEmployeeCommunications
     SET
		MobileNumber=@rMobileNo,
		CompanyEmail=@rEmailId,
		UpdatedUserId=@rCreatedUserId,
		UpdatedDateTime=@lCurrentDateTime
      WHERE (EmployeeId = @rEmployeeId) 
      SELECT 1 AS Result
      RETURN
     END

	BEGIN TRY
	
	 BEGIN TRANSACTION

IF(@rId = 0)	
BEGIN
	
	DECLARE @lNextNumber BIGINT	
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 101, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sSecurity.tUser
		(
			Id,		
			DisplayTitle,
			LoginTitle,
			LoginPassword,
			LastLockOutDate,
			NumberOfLogonAttempt,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId,
			SourceTypeId,
			SourceId
        )
	VALUES
		(
			@lNextNumber,
			@rName,					
			@rUserName,
			@rLoginPassword,
			@lCurrentDateTime,
			0,
			@rIsObsolete,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rOrgId,
			95,
			@rEmployeeId
		)
		
		INSERT INTO sSecurity.tUserRole
		(
			RoleId,
			UserId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsPrimary
		)
		VALUES
		(
			@rRoleId,
			--sCommon.fGetIntIdForOrg(10,@rOrgGroupId),
			@lNextNumber,
			@rIsObsolete,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rCreatedUserId,
			@lCurrentDateTime,
			1
		)
		              
	END	 
	 ELSE
	 BEGIN
	 
	 SET @lNextNumber = @rId
	    UPDATE  sSecurity.tUser
	    SET
			LoginTitle=@rUserName,
			LoginPassword=@rLoginPassword,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=@lCurrentDateTime
	      WHERE (Id = @rId) 
	 END  
	 
	 UPDATE sHrm.tEmployeeCommunications
     SET
		MobileNumber=@rMobileNo,
		CompanyEmail=@rEmailId,
		UpdatedUserId=@rCreatedUserId,
		UpdatedDateTime=@lCurrentDateTime
      WHERE (EmployeeId = @rEmployeeId) 
      
		SELECT @lNextNumber AS Result
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSecurity].[pStudentPasswordAdd]...';


GO

ALTER PROCEDURE [sSecurity].[pStudentPasswordAdd]
	
	@rId bigint,
	@rStudentId bigint,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rName nvarchar(100),
	@rEmailId nvarchar(100),
	@rMobileNo nvarchar(20),
	@rUserName nvarchar(100),
	@rLoginPassword nvarchar(100),
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rIsFullUpdate bit

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	  
	
		IF(@rId = 0)	
		BEGIN
			IF(@rStudentId <> 0)
			BEGIN
				IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceTypeId = 2003 AND SourceId = @rStudentId AND OrgId=@rOrgId)
				BEGIN
					SELECT -101 AS UserId
					RETURN
				END
			END
		
			IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rUserName AND OrgId = @rOrgId)
			BEGIN
				SELECT -101 AS UserId
				RETURN
			END
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rUserName AND OrgId = @rOrgId AND Id<>@rId)
			BEGIN
				SELECT -101 AS UserId
				RETURN
			END
		END
	 
	 DECLARE @lCurrentDateTime DATETIME
	 EXECUTE @lCurrentDateTime = sCommon.fGetDate
	 --IF(@rIsFullUpdate=0)
	 --BEGIN
	 --UPDATE sStudent.tStudentCommunication
  --   SET
		--ParentContactNo=@rMobileNo,
		--ParentEmail=@rEmailId,
		--UpdatedUserId=@rCreatedUserId,
		--UpdatedDateTime=@lCurrentDateTime
  --    WHERE (StudentId = @rStudentId) 
	 -- SELECT 1 AS Result
  --    RETURN
  --   END
     
     BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
--SELECT @rId = ID FROM sSecurity.tUser WHERE SourceId = @rStudentId And SourceTypeId = 2003
     
IF NOT EXISTS( SELECT 1 FROM sSecurity.tUser WHERE SourceId = @rStudentId And SourceTypeId = 2003 And OrgId = @rOrgId)	
BEGIN
	
	DECLARE @lNextNumber BIGINT	
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 101, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sSecurity.tUser
		(
			Id,		
			DisplayTitle,
			LoginTitle,
			LoginPassword,
			LastLockOutDate,
			NumberOfLogonAttempt,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId,
			SourceTypeId,
			SourceId
        )
	VALUES
		(
			@lNextNumber,
			@rName,					
			@rUserName,
			@rLoginPassword,
			@lCurrentDateTime,
			0,
			@rIsObsolete,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rOrgId,
			2003,
			@rStudentId
		)
		
		INSERT INTO sSecurity.tUserRole
		(
			RoleId,
			UserId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsPrimary
		)
		VALUES
		(
			sCommon.fGetIntIdForOrg(22,@rOrgGroupId),
			@lNextNumber,
			@rIsObsolete,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rCreatedUserId,
			@lCurrentDateTime,
			1
		)
		    
	END	 
	 ELSE
	 BEGIN
	 
	 --UPDATE sStudent.tStudentCommunication
  --   SET
		--ParentContactNo=@rMobileNo,
		--ParentEmail=@rEmailId,
		--UpdatedUserId=@rCreatedUserId,
		--UpdatedDateTime=@lCurrentDateTime
  --    WHERE (StudentId = @rStudentId) 
	 
	 SET @lNextNumber = @rId
	    UPDATE  sSecurity.tUser
	    SET
			LoginTitle=@rUserName,
			LoginPassword=@rLoginPassword,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=@lCurrentDateTime
	      WHERE (Id = @rId) 
	 END  
		SELECT @lNextNumber AS Result
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSecurity].[pUserAdd]...';


GO
ALTER PROCEDURE [sSecurity].[pUserAdd]
	@rOrgId [smallint],
	@rDisplayTitle [nvarchar](100),
	@rLoginTitle [nvarchar](20),
	@rLoginPassword [nvarchar](100),
	@rIsObsolete [bit],
	--@rEmployeeId [int],
	@rUserSourceId bigint,
	@rUserSourceTypeId int,
	@rCreatedUserId [bigint],
	@rValidUpto date,
	@rIsCommon bit
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rUserSourceTypeId=0)
	BEGIN
		SET @rUserSourceId=NULL
		SET @rUserSourceTypeId=NULL
	END
	
	IF((@rUserSourceTypeId <> 1 OR @rUserSourceId<>0))
	BEGIN
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceTypeId = @rUserSourceTypeId AND SourceId = @rUserSourceId AND OrgId=@rOrgId)
		BEGIN
			SELECT -1 AS UserId
			RETURN
		END
	END
	
	IF(@rIsCommon=0)
	BEGIN
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rLoginTitle AND OrgId = @rOrgId)
		BEGIN
			SELECT -1 AS UserId
			RETURN
		END
	END
	IF(@rIsCommon=1)
	BEGIN
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE DisplayTitle = @rDisplayTitle OR LoginTitle = @rLoginTitle)
		BEGIN
			IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceId != NULL AND SourceTypeId != NULL)
			BEGIN
				SELECT -1 AS UserId
				RETURN
			END
			ELSE IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE (DisplayTitle = @rDisplayTitle OR LoginTitle = @rLoginTitle) AND OrgId=@rOrgId)
			BEGIN
				SELECT -1 AS UserId
				RETURN
			END
		END
	END
	
	DECLARE @lNextNumber BIGINT	
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 101, 1,@outNextNumber = @lNextNumber output
	
	DECLARE @lCurrentDateTime DATETIME
	EXECUTE @lCurrentDateTime = sCommon.fGetDate		

		INSERT INTO sSecurity.tUser
			(
				Id,		
				DisplayTitle,
				LoginTitle,
				LoginPassword,
				LastLockOutDate,
				NumberOfLogonAttempt,
				IsObsolete,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				--EmployeeId,
				OrgId,
				SourceId,
				SourceTypeId,
				ValidUpto,
				IsCommon
			)
		VALUES
			(
				@lNextNumber,
				@rDisplayTitle,					
				@rLoginTitle,
				@rLoginPassword,
				@lCurrentDateTime,
				0,
				@rIsObsolete,
				@rCreatedUserId,
				@lCurrentDateTime,
				@rCreatedUserId,
				@lCurrentDateTime,
				--@rEmployeeId,
				@rOrgId,
				@rUserSourceId,
				@rUserSourceTypeId,
				@rValidUpto,
				@rIsCommon
			)
			
			
			IF(@rUserSourceTypeId=1  OR  @rUserSourceTypeId=95)
			BEGIN
			IF NOT EXISTS(SELECT 1 FROM sSecurity.tUserOrganization WHERE UserId = @lNextNumber AND OrgId = @rOrgId)
			BEGIN
			INSERT INTO sSecurity.tUserOrganization
			SELECT @rOrgId,@lNextNumber
			END
			END
			
			
	SELECT @lNextNumber AS UserId
END
GO
PRINT N'Altering [sSecurity].[pUserLogAdd]...';


GO
ALTER PROCEDURE [sSecurity].[pUserLogAdd]
	@rOrgId int,
	@rUserId bigint,
	@rLoggedInIp [nvarchar](15),
	@rIsOnlinep [bit],
	@rLoggedInDateTime [datetime],
	@rLoggedOutDateTime [datetime],
	@rUiCultureIdp [tinyint],
	@rSessionIdp [nvarchar](100),
	@rLocalAddress [nvarchar](200)=''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId,'sSecurity.tUserLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	--SELECT @lNextNumber

BEGIN
	INSERT INTO sSecurity.tUserLog
		(
			OrgId,
			Id,
			UserId,
			LoggedInIp,
			LoggedInDateTime,
			LoggedOutDateTime,
			IsOnline,
			UiCultureId,
			SessionId,
			LoggedInLocalIp
		)
	VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rUserId,
			@rLoggedInIp,
			@rLoggedInDateTime,
			@rLoggedOutDateTime,
			@rIsOnlinep,
			@rUiCultureIdp,
			@rSessionIdp,
			@rLocalAddress
		)
END
GO
PRINT N'Altering [sSecurity].[pUserValidate]...';


GO
 
ALTER PROCEDURE [sSecurity].[pUserValidate]
	@rOrgId int,
	@rUserTitle [nvarchar](100),
	@rUserPassword [nvarchar](1000),
	@rHostAddress [nvarchar](100),	
	@rSessionId [nvarchar](100),
	@rLocalAddress [nvarchar](100)=''
	
WITH EXECUTE AS CALLER
AS
DECLARE @lUserId BIGINT
SET @lUserId = 0

DECLARE @lLoginAttempts INT	
SET @lLoginAttempts = 0

DECLARE @lLoginDateTime DateTime
SET @lLoginDateTime = sCommon.fGetDate()

DECLARE @lLastLockoutDate DateTime
SET @lLastLockoutDate = NULL

DECLARE @lValidUpto Date
SET @lValidUpto = NULL


DECLARE @lOrgGroupId int=0
SELECT @lOrgGroupId=OrgGroupId  FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId

DECLARE @lItemValue nvarchar(20) = ''
SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
FROM sConfig.tConfigurationMaster CM
LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
AND SourceTypeId = 2010 AND SourceId = 1001 WHERE CM.Id = 224

DECLARE @lTimePolicyId int
DECLARE @lIpPolicyId int
DECLARE @lAccessTime nvarchar(300)

DECLARE @lTimePolicy TABLE(Id int identity, AccessTime nvarchar(100))
DECLARE @lIpPolicyDetail TABLE(IP nvarchar(100))



SET NOCOUNT ON

BEGIN
	SELECT 
		@lUserId = Id,
		@lValidUpto = ValidUpto
	FROM sSecurity.tUser 		
	WHERE 
		    UPPER(LoginTitle) = UPPER(@rUserTitle) AND
		   	(LoginPassword = @rUserPassword  OR @rUserPassword = '')  AND 
			NumberOfLogonAttempt <= 5000 AND
			IsObsolete = 0 AND
			OrgId = @rOrgId
	IF @lUserId > 0
		BEGIN
			
			SELECT 
				@lTimePolicyId = TimePolicyId ,@lIpPolicyId = IpPolicyId 
			FROM sSecurity.tUserPolicy 
				WHERE  UserId = @lUserId
			
			IF(@lTimePolicyId IS NOT NULL AND @lTimePolicyId !=0)	
			BEGIN
				SELECT @lAccessTime = AccessTime FROM sSecurity.tTimePolicy	WHERE  Id = @lTimePolicyId
				INSERT @lTimePolicy SELECT * FROM sCommon.fnSplit(@lAccessTime,',')
				DECLARE @lCount int 
				SELECT @lCount = COUNT(AccessTime) FROM @lTimePolicy
				DECLARE @LoopCounter INT = 1
				DECLARE @lIsValid bit = 0
				
				WHILE (@LoopCounter <= @lCount)
				BEGIN
						
					DECLARE @lTime nvarchar(100)
					SELECT @lTime = AccessTime FROM @lTimePolicy WHERE Id = @LoopCounter
					DECLARE @lFromTime nvarchar(100)
					DECLARE @lToTime nvarchar(100)
					SELECT @lFromTime = SUBSTRING(@lTime, 1, 5 )
					SELECT @lToTime = SUBSTRING(@lTime, 7, 10 )
					IF(CONVERT(time,getdate()) BETWEEN CONVERT(time,@lFromTime) AND CONVERT(time,@lToTime))
					BEGIN	
						SET @lIsValid = 1
					END 
					ELSE IF(@lIsValid=0)
					BEGIN 
						RAISERROR('Not allowed due to time policy constrain', 16, 1)
						RETURN
					END 
					 SET @LoopCounter  = @LoopCounter  + 1
				END
			END
			
			IF(@lIpPolicyId IS NOT NULL AND @lIpPolicyId !=0)	
			BEGIN
				
				
				INSERT @lIpPolicyDetail SELECT IP FROM sSecurity.tIpPolicyDetail WHERE  IpPolicyId = @lIpPolicyId
				
				IF(@lItemValue='False')
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM @lIpPolicyDetail WHERE IP = @rHostAddress)
					BEGIN 
						RAISERROR('Not allowed due to ip policy constrain', 16, 1)
						RETURN
					END
				END
				ELSE
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM @lIpPolicyDetail WHERE IP = @rLocalAddress)
					BEGIN 
						RAISERROR('Not allowed due to ip policy constrain', 16, 1)
						RETURN
					END
				END
			END
			
			IF(@lValidUpto IS NOT NULL)
			BEGIN
				IF(CONVERT(date, getdate()) > @lValidUpto)
				BEGIN
					RAISERROR('Your Account is expired', 16, 1)
					RETURN
				END
			END
			
			--UPDATE sSecurity.tUser
			--SET IsOnline = 1,
			--	NumberOfLogonAttempt = 0,			
			--	UpdatedDate = sCommon.fGetDate()
			--WHERE Id = @lUserId
			IF(@lUserId != 1 AND @rUserTitle != 'SysSuperAdmin')
			BEGIN
			EXECUTE sSecurity.pUserLogAdd @rOrgId, @lUserId, @rHostAddress, 1, @lLoginDateTime, NULL, 1, @rSessionId,@rLocalAddress
			END
			--INSERT INTO sSecurity.tUserLog(UserId, LoggedInIp, LoggedInDateTime)
			--VALUES (@lUserId, @rHostAddress, sCommon.fGetDate())

	--		SELECT Id, Title, TitleResourceKey 
	--		FROM sSecurity.tRole 
	--		INNER JOIN sSecurity.tUserRole
	--			ON RoleId = Id
	--		WHERE UserId = @lUserId AND sSecurity.tRole.IsObsolete = 0
			
		 --   UPDATE E
			--SET E.StatusId = 9
			--FROM sHrm.tEmployeeMaster E
			--JOIN sHrm.tEmployeeJobDetail J ON E.Id = J.EmployeeId 
			--WHERE 
			----J.activeupto <= getdate() and 
			--E.orgID= @rOrgId 	    
		    
			SELECT @lUserId 
		END
	ELSE
		BEGIN 
			SELECT @lUserId = Id,
					@lLoginAttempts = NumberOfLogonAttempt,
					@lLastLockoutDate = LastLockOutDate
			FROM sSecurity.tUser
			WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND
					OrgId = @rOrgId
			
			IF @lUserId > 0
				BEGIN
					IF @lLoginAttempts > 250
						BEGIN
							IF @lLastLockoutDate IS NULL
								BEGIN
									UPDATE sSecurity.tUser
									SET LastLockOutDate = sCommon.fGetDate(),
										UpdatedDateTime = sCommon.fGetDate()
									WHERE Id = @lUserId AND
										 OrgId = @rOrgId
								END
							RAISERROR('User account locked', 16, 1)
							RETURN
						END
					ELSE
						BEGIN
							UPDATE sSecurity.tUser
							SET NumberOfLogonAttempt = NumberOfLogonAttempt + 1,
								UpdatedDateTime = sCommon.fGetDate()
							WHERE Id = @lUserId AND
								OrgId = @rOrgId
						END
				END		

			RAISERROR('Username/password does not match or Inactive user.', 16, 1)		
		END
END
GO
PRINT N'Altering [sSetup].[pOrganizationMasterAdd]...';


GO
ALTER PROCEDURE [sSetup].[pOrganizationMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rDisplayTitle nvarchar(100),
	@rAffiliationId smallint,
	@rLanguageId smallint,
	--@rInstituteTypeId smallint,
	--@rInstituteSubTypeId smallint,
	@rStreetOne nvarchar(50),
	@rStreetTwo nvarchar(50),
	@rStreetThree nvarchar(50),
	@rCityName nvarchar(100),
	@rStateName nvarchar(100),
	@rCountryName nvarchar(100),
	@rZipCode nvarchar(20),
	@rHomePage nvarchar(100),
	@rPhoneNo nvarchar(50),
	@rFaxNo nvarchar(50),
	@rReportOrgTitle nvarchar(200),
	@rSmallAddress1 nvarchar(100),
	@rSmallAddress2 nvarchar(100),
	@rRegistrationDetail nvarchar(200),
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rIsObsolete bit,
	@rOrgGroupId smallint,
	@rOrgLogo varbinary(max),
	@rIsLogo bit,
	@rEmployeeId bigint,
	@rOrderIndex int,
	--@rIcardOrgTitle nvarchar(200),
	--@rIcardAddress1 nvarchar(200),
	--@rIcardAddress2 nvarchar(200),
	--@rICardAddress3 nvarchar(200),
	--@rLabelColor nvarchar(20),
	--@rDetailColor nvarchar(20),
	--@rHeaderColor nvarchar(20),
	@rOrgSubGroupId int=0,
	@rTermPatternId int=0,
	@rNameFormateId tinyint = 1,
	@rWeekOffs nvarchar(20),
	@rReportOrgGroupTitle nvarchar(200)='',
	@rDegreeAwarded nvarchar(100) = '',
	@rShortCode nvarchar(20) = '',
	@rNoOfTerm tinyint=0,
	@rHeadMargin int=0,
	@rUniversity nvarchar(100)='',
	@rFooterSignature nvarchar(500)='',
	@rEmail nvarchar(150) = null,
	@rTaxOfficeDetail nvarchar(500) = null,
	@rTANNumber nvarchar(40) = null,
	@rPANNumber nvarchar(40)=null,
	@rTaxCertifyAuthorityName        nvarchar(100)=null,
	@rTaxCertifyAuthorityFatherName  nvarchar(100)=null,
	@rTaxCertifyAuthorityRelation    nvarchar(100)=null,
	@rTaxCertifyAuthorityDesignation nvarchar(100)=null,
	@rOrgTypeCaption nvarchar(100)='',
	@rAccountNumber nvarchar(50)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF EXISTS (SELECT 1 FROM sSetup.tOrganizationMaster WHERE @rId = 0 AND Code=@rCode)
	BEGIN
		SELECT -100 AS RESULT
		RETURN
	END

	BEGIN TRY
	
	BEGIN TRANSACTION	
	
	
	IF(@rId=0)
	BEGIN
	SET @rId=@rCode
		 
	INSERT INTO sSetup.tOrganizationMaster
		(
			Id,
			Code,
			Title,
			DisplayTitle,
			AffiliationId,
			LanguageId,
			--InstituteTypeId,
			--InstituteSubTypeId,
			StreetOne,
			StreetTwo,
			StreetThree,
			CityName,
			StateName,
			CountryName,
			ZipCode,
			HomePage,
			PhoneNo,
			FaxNo,
			ReportOrgTitle,
			SmallAddress1,
			SmallAddress2,
			RegistrationDetail,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			OrgGroupId,
			EmployeeId,
			OrderIndex,
			--,
			--IcardOrgTitle,
		



	--IcardAddress1,
			--IcardAddress2,
			--ICardAddress3,
			--LabelColor,
			--DetailColor,
			--HeaderColor,
			OrgSubGroupId,
			TermPatternId,
			StudentNameFormatId,
			WeekOffs,
			ReportOrgGroupTitle,
			DegreeAwarded,
			ShortCode,
			NoOfTerm,
			LetterHeadMargin,
			University,
			FooterSignature,
			Email,
			OrgTypeCaption
			--OrgLogo
		)
	VALUES
		(
			@rCode,
			@rCode,
			@rTitle,
			@rDisplayTitle,
			@rAffiliationId,
			@rLanguageId,
			--@rInstituteTypeId,
			--@rInstituteSubTypeId,
			@rStreetOne,
			@rStreetTwo,
			@rStreetThree,
			@rCityName,
			@rStateName,
			@rCountryName,
			@rZipCode,
			@rHomePage,
			@rPhoneNo,
			@rFaxNo,
			--@rReportOrgTitle,
			@rTitle,
			@rSmallAddress1,
			@rSmallAddress2,
			@rRegistrationDetail,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId,
			@rEmployeeId,
			@rOrderIndex,
			--,
			--@rIcardOrgTitle,
			--@rIcardAddress1,
			--@rIcardAddress2,
			--@rIcardAddress3,
			--@rLabelColor,
			--@rDetailColor,
			--@rHeaderColor,
			@rOrgSubGroupId,
			@rTermPatternId,
			1,
			ISNULL(@rWeekOffs,'0'),
			@rReportOrgGroupTitle,
			@rDegreeAwarded,
			@rShortCode,
			@rNoOfTerm,
			@rHeadMargin,
			@rUniversity,
			@rFooterSignature,
			@rEmail,
			@rOrgTypeCaption
			--@rOrgLogo
		)
		 EXECUTE [sCommon].[pOrganizationSetupAdd] @rId
		 --print @rId
		 
		 
		 DECLARE @lIsCommonToAll bit = 0
	     DECLARE @lConfigValue nvarchar(50)
	     SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 139 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	     
	     IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
			SET @lIsCommonToAll = 0
		 ELSE
			SET @lIsCommonToAll = 1
		 
		 -- For SMS Configuration
		 
		 DECLARE @lCountSMS int=0, @lOrgIdSMS int
		 
		 SELECT @lCountSMS = COUNT(OrgId) FROM sAlert.tSMSConfiguration
		 
		 IF(@lCountSMS!=0 AND @lIsCommonToAll = 1)
		 BEGIN
			SELECT TOP 1 @lOrgIdSMS = OrgId FROM sAlert.tSMSConfiguration
			
			INSERT INTO sAlert.tSMSConfiguration
			SELECT 
				@rCode,
				SMSURL,
				SMSCreditURL,
				LoginId,
				LoginPassword,
				LoginSenderId,
				SMSXMLURL,
				VendorId,
				SMSUnicodeURL
			FROM sAlert.tSMSConfiguration SMS
			INNER JOIN sSetup.tOrganizationMaster OM ON SMS.OrgId = OM.Id
			WHERE OrgId = @lOrgIdSMS AND OM.OrgGroupId = @rOrgGroupId
			
		 END
		 
		 -- For Email Configuration
		 
		 DECLARE @lCountEmail int=0, @lOrgIdEmail int
		 SELECT @lCountEmail = COUNT(OrgId) FROM sAlert.tEmailConfiguration
		 
		 IF(@lCountEmail!=0 AND @lIsCommonToAll = 1)
		 BEGIN
			SELECT TOP 1 @lOrgIdEmail = OrgId FROM sAlert.tEmailConfiguration
			
			INSERT INTO sAlert.tEmailConfiguration
			SELECT 
				@rCode,
				MailTypeId,
				SMTPServer,
				SMTPPort,
				EnableSSL,
				SendUserName,
				SendPassword,
				FromMail
			FROM sAlert.tEmailConfiguration Email
			INNER JOIN sSetup.tOrganizationMaster OM ON Email.OrgId = OM.Id
			WHERE OrgId = @lOrgIdEmail AND OM.OrgGroupId = @rOrgGroupId
		 END
		
		 
		 SELECT @rCode AS Result
		             
	END	 
	 ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	    UPDATE  sSetup.tOrganizationMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			DisplayTitle=@rDisplayTitle,
			AffiliationId=@rAffiliationId,
			LanguageId=@rLanguageId,
			--InstituteTypeId=@rInstituteTypeId,
			--InstituteSubTypeId=@rInstituteSubTypeId,
			StreetOne=@rStreetOne,
			StreetTwo=@rStreetTwo,
			StreetThree=@rStreetThree,
			CityName=@rCityName,
			StateName=@rStateName,
			CountryName=@rCountryName,
			ZipCode=@rZipCode,
			HomePage=@rHomePage,
			PhoneNo=@rPhoneNo,
			FaxNo=@rFaxNo,
			ReportOrgTitle=@rReportOrgTitle,
			SmallAddress1=@rSmallAddress1,
			SmallAddress2=@rSmallAddress2,
			RegistrationDetail=@rRegistrationDetail,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete,
			OrgGroupId=@rOrgGroupId,
			EmployeeId=@rEmployeeId,
			OrderIndex=@rOrderIndex,	 
			--IcardOrgTitle=@rIcardOrgTitle,
			--IcardAddress1=@rIcardAddress1,
			--IcardAddress2=@rIcardAddress2,
			--IcardAddress3=@rIcardAddress3,
			--LabelColor=@rLabelColor,
			--DetailColor=@rDetailColor,
			--HeaderColor=@rHeaderColor,
			OrgSubGroupId=@rOrgSubGroupId,
			TermPatternId=@rTermPatternId,
			StudentNameFormatId= @rNameFormateId,
			WeekOffs=@rWeekOffs,
			ReportOrgGroupTitle=@rReportOrgGroupTitle,
			DegreeAwarded=@rDegreeAwarded,
			ShortCode =@rShortCode,
			NoOfTerm = @rNoOfTerm,
			LetterHeadMargin = @rHeadMargin,
			University = @rUniversity,
			Footersignature= @rFooterSignature,
			Email=@rEmail,
			OrgTypeCaption=@rOrgTypeCaption
			--OrgLogo=@rOrgLogo
	      
	      
	      WHERE Id = @rId 
	      
		  UPDATE  sHrm.tEmployeeJobDetail  SET EmployeeBusinessHeadId=@rEmployeeId  where OrgId=@rId

		  IF NOT EXISTS (SELECT 1 FROM sSetup.tOrganizationOtherDetail WHERE OrgId = @rId )
			  BEGIN
				INSERT INTO sSetup.tOrganizationOtherDetail  (OrgId,PANNumber,TANNumber,TaxOfficeDetail,TaxCertifyAuthorityName,TaxCertifyAuthorityFatherName,TaxCertifyAuthorityRelation,TaxCertifyAuthorityDesignation,AccountNumber)
				VALUES (@rId,@rPANNumber,@rTANNumber,@rTaxOfficeDetail,@rTaxCertifyAuthorityName,@rTaxCertifyAuthorityFatherName,@rTaxCertifyAuthorityRelation,@rTaxCertifyAuthorityDesignation,@rAccountNumber)
			  END
		 ELSE 
		 BEGIN
			 UPDATE sSetup.tOrganizationOtherDetail SET TaxOfficeDetail=@rTaxOfficeDetail,
				TANNumber=@rTANNumber,
				PANNumber=@rPANNumber,
				TaxCertifyAuthorityName=@rTaxCertifyAuthorityName,
				TaxCertifyAuthorityFatherName=@rTaxCertifyAuthorityFatherName,
				TaxCertifyAuthorityRelation=@rTaxCertifyAuthorityRelation,
				TaxCertifyAuthorityDesignation=@rTaxCertifyAuthorityDesignation,
				AccountNumber=@rAccountNumber
			 Where OrgId=@rId
		 END



		  



	      IF(@rIsLogo = 1)
	      BEGIN
			UPDATE  sSetup.tOrganizationMaster
				SET
					OrgLogo=@rOrgLogo
			WHERE Id = @rId 
	      END
	      
	      SELECT @rId AS Result	   
	 END  
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pRptStudentIcardGet]...';


GO



ALTER PROCEDURE [sStudent].[pRptStudentIcardGet]
	 
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rHouseGroupId int=0,
	 @rIsShowBarcode bit=0,
	 @rOrgGroupBatchId int
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @lIcardBorder nvarchar(10)
DECLARE @lSUIdBarcode nvarchar(50)
--DECLARE @lIsBarcodeBasedOnSUId bit = 0
DECLARE @lOrgGroupId int = 0

SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId


SELECT @lIcardBorder = ItemValue FROM sConfig.tConfigurationSetup WHERE configurationId = 130 AND SourceTypeId = 1016 AND SourceId = @rOrgId --ItemKey = 'sConfig.tConfigurationSetup' 
SELECT @lSUIdBarcode = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 168 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	
	--IF (@lSUIdBarcode IS NULL) OR (@lSUIdBarcode = 'False')
	--SET @lIsBarcodeBasedOnSUId = 0
	--ELSE
	--SET @lIsBarcodeBasedOnSUId = 1	
	
	SELECT			 
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassName,
			SD.DivisionName,
			SD.ClassDivision,
			SD.Batch,
			SD.Code,
			SD.Number AS StudentNumber,
			SD.RegistrationNumber,	
			SD.RollNo,				
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.FirstName + ' ' + SD.MiddleName + ' ' + SD.LastName As Name,		 
			SD.StatusId,
			SD.DateOfBirth,		
			SD.BloodGroup,
			ISNULL(SD.PresentStreetone,'') AS PresentStreetone,
			ISNULL(SD.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(SD.PresentStreetThree,'') AS PresentStreetThree,
		    ISNULL(SD.PresentCity,'') AS PresentCity,
		    ISNULL(SD.PresentZipCode,'') AS PresentZipCode,
			SD.PresentContactNo,						 
			SD.ParentContactNo AS ParentContactNo,
			SD.StudentContactNo,			
			SD.StudentPhoto,
			SD.AdmissionCategory, 
			SD.DivisionOrder,		 
			OM.Title AS OrgName,	
			ISNULL(HM.Title,'') AS HouseName,	
			OM.PrincipalSignature,
			ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,
			ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,
			ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,
			ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,			
			OM.OrgLogo AS ICardLogo,
			
			--ISNULL(ICO.ICardBackground,0) AS ICardBackground,	
			--ISNULL(ICO.ICardBackBackground,0) AS ICardBackBackground,	
			
			 ICO.ICardBackground  AS ICardBackground,	
			 ICO.ICardBackBackground  AS ICardBackBackground,						
			  
			ISNULL(ICO.LabelColor,'Black') AS LabelColor,
			ISNULL(ICO.DetailColor,'Black') AS DetailColor,
			ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(RT.RouteName,'') AS RouteName,
			ISNULL(RT.PickupPoint,'') AS PickupPoint,
			@lIcardBorder AS IcardBorder,
			HM.ColorCode,
			OM.OrgLogo,
			OM.SmallAddress1,
			--@lSUIdBarcode AS IsBarcodeBasedOnSUId,
			CASE WHEN @lSUIdBarcode = 'True' THEN SD.SUId  ELSE SD.Code END AS BarcodeNumber,
			 ISNULL(SD.EmergencyStreetOne,'') AS EmergencyStreetOne,
	         ISNULL(SD.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
	        ISNULL(SD.EmergencyStreetThree,'') AS EmergencyStreetThree,
	        ISNULL(SD.EmergencyCountry,'') AS EmergencyCountry,
	        ISNULL(SD.EmergencyState,'') As EmergencyState,
	        ISNULL(SD.EmergencyCity,'') AS EmergencyCity,
	        ISNULL(SD.EmergencyZipCode,'') as EmergencyZipCode,
	        SD.EmergencyContactNo AS EmergencyContactNo,
			ISNULL(SD.SUId,'') As SUId,
			ISNULL(RT.RouteNumber,0) AS RouteNumber,
			@rIsShowBarcode As IsShowBarcode,
			SD.Name,
			SM.Title AS Stream,
			SD.AdmissionDate,
			ISNULL(DM.Title,'') AS DepartmentName,
			SD.FatherPhoto,
			SD.MotherPhoto
			
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			--INNER JOIN sStudent.tStudentOther SO ON SD.StudentId = So.StudentId 			
			LEFT JOIN sActivity.tHouseMaster HM ON SD.HouseId = HM.Id 
			LEFT JOIN sActivity.tHouseGroupMaster HGM ON HGM.Id=HM.HouseGroupId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SD.StudentId 
			 LEFT JOIN
			(SELECT AT.SourceId,BRM.Title As RouteName,BRDM.Title As PickupPoint,ISNULL(BRM.RouteNumber,0) AS RouteNumber FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND  AT.SourceTypeId=2003 AND ((BRM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SD.StudentId AND ((SD.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		 
			--LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId =SD.StudentId 
			--LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id =AR.PickupDestinationId 
			--LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id =BRDM.BusRouteId  AND(( BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			LEFT JOIN sStudent.tICardOrg ICO ON SD.OrgId = ICO.OrgId
			LEFT JOIN sSetup.tStreamMaster SM ON SM.Id=SD.StreamId
			LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id=SD.DepartmentId
			
	
			--LEFT JOIN sSetup.tOrganizationConfiguration OC ON OM.Id = OC.OrgId 
			
	WHERE 
		SD.OrgId=@rOrgId
		AND	SD.BatchId = @rBatchId 
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((HGM.Id=@rHouseGroupId)OR(@rHouseGroupId=0))
END
GO
PRINT N'Altering [sStudent].[pRptStudentWithoutHostelTransportGet]...';


GO

ALTER PROCEDURE [sStudent].[pRptStudentWithoutHostelTransportGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrStudentId nvarchar(max),
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rOrgGroupBatchId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,
			SA.Code,
			SA.RollNo AS RollNo,			
			SA.FirstName,			
			SA.LastName,
			SA.Name,		
			SA.ClassName,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber
      
	FROM  sStudent.vStudentLastAcademic SA
			WHERE 
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		
		 EXCEPT
		SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,
			SA.Code,
			SA.RollNo AS RollNo,			
			SA.FirstName,			
			SA.LastName,
			SA.Name,		
			SA.ClassName,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber
			 FROM sHostel.tAssignRoom AR  INNER JOIN sStudent.vStudentLastAcademic SA ON  SA.StudentId=AR.SourceId  WHERE  AR.SourceTypeId = 2003 
			 AND AR.OrgGroupBatchId=@rOrgGroupBatchId  AND SA.OrgGroupBatchId=@rOrgGroupBatchId
			  
			EXCEPT
	  SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,
			SA.Code,
			SA.RollNo AS RollNo,			
			SA.FirstName,			
			SA.LastName,
			SA.Name,		
			SA.ClassName,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber
			 FROM sTransport.tAssignRoute  TA 
			    INNER JOIN sTransport.tBusRouteDestinationMaster BRM ON BRM.Id=TA.PickupDestinationId
			    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BRM.BusRouteId 
			    INNER JOIN  sStudent.vStudentLastAcademic SA ON  SA.StudentId=TA.SourceId  WHERE  TA.SourceTypeId = 2003
			    AND SA.OrgGroupBatchId=@rOrgGroupBatchId   AND B.OrgGroupBatchId=@rOrgGroupBatchId
			  
			
END
GO
PRINT N'Altering [sStudent].[pStudentCustomSearchGet]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentCustomSearchGet]
(
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9990-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9990-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9990-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount Smallint=0,
	@rStudentStatus Smallint=0,
	@rHostelId nvarchar(max) = '',
	@rFatherName nvarchar(50)='',
	@rMotherName nvarchar(50)='',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption  nvarchar(max) = ''
 )
AS
SET NOCOUNT ON

BEGIN
		DECLARE @Sql nvarchar(MAX)
		
		IF(@rDOBFromDate IS NULL)
			SET @rDOBFromDate='0001-01-01'
		IF(@rDOBToDate IS NULL)
			SET @rDOBToDate='9990-12-31'
		IF(@rDOAFromDate IS NULL)
			SET @rDOAFromDate='0001-01-01'
		IF(@rDOAToDate IS NULL)
			SET @rDOAToDate='9990-12-31'
		IF(@rDOLFromDate IS NULL)
			SET @rDOLFromDate='0001-01-01'
		IF(@rDOLToDate IS NULL)
			SET @rDOLToDate='9990-12-31'
		
		 
		SET @rDOBToDate = DATEADD(d,1,@rDOBToDate)		 
		SET @rDOAToDate = DATEADD(d,1,@rDOAToDate)		 
		SET @rDOLToDate = DATEADD(d,1,@rDOLToDate)	
		
		
	
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rCountry = sCommon.fSearchStringGet(@rCountry)
		SET @rState = sCommon.fSearchStringGet(@rState)
		 
		-- For Custom Tag
		IF (@rCustomTagId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId1
			INTO sStudent.tTempStudent2
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		END
		
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId1
			INTO sStudent.tTempStudent2
		END
			 
		-- For Custom Group
		IF (@rCustomGroupId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId2
			INTO sStudent.tTempStudent3
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId2
			INTO sStudent.tTempStudent3
		END
		
		-- For Club Group
		IF (@rClubId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId3
			INTO sStudent.tTempStudent4
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId3
			INTO sStudent.tTempStudent4
		END
		
		-- For Hostel
		IF (@rHostelId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId4
			INTO sStudent.tTempStudent8
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
			AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
			WHERE SM.OrgId = @rOrgId --AND A.BatchId = @BatchId 
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId4
			INTO sStudent.tTempStudent8
		END
		--Transport
		IF (@rBusRouteId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId5
			INTO sStudent.tTempStudent9
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
			AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE SM.OrgId = @rOrgId 
			AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId5
			INTO sStudent.tTempStudent9
		END
	
		IF (@rFeeExemption <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId6
			INTO sStudent.tTempStudent10
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sFee.tExemptionTypeMaster AT ON AT.Id = A.ExemptionTypeId
			 
			WHERE SM.OrgId = @rOrgId 
			AND (ISNULL(AT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId6
			INTO sStudent.tTempStudent10
		END
		
		SELECT 
				*,
				SCS.ClassName+'-'+SCS.DivisionName AS ClassName1
		INTO sStudent.tTempStudent1
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent2 T2 ON SCS.StudentId = T2.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent3 T3 ON SCS.StudentId = T3.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent4 T4 ON SCS.StudentId = T4.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent8 T8 ON SCS.StudentId = T8.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId5 OR @rBusRouteId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId6 OR @rFeeExemption = ''
		WHERE 
			SCS.OrgId = @rOrgId AND SCS.BatchId = @BatchId 
			AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%')OR(@rCountry = ''))
			AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))		 
			AND (( SCS.DateOfBirth  >= @rDOBFromDate) OR (ISNULL(SCS.DateOfBirth,'') = ''))
			AND (( SCS.DateOfBirth  < @rDOBToDate) OR (ISNULL(SCS.DateOfBirth,'') = ''))
			AND (( SCS.AdmissionDate >= @rDOAFromDate) OR (ISNULL(SCS.AdmissionDate,'') = ''))
			AND (( SCS.AdmissionDate < @rDOAToDate) OR (ISNULL(SCS.AdmissionDate,'') = ''))		 
			AND (( SCS.LeftDate  >= @rDOLFromDate) OR (ISNULL(SCS.LeftDate,'') = ''))
			AND (( SCS.LeftDate   < @rDOLToDate) OR (ISNULL(SCS.LeftDate,'') = ''))
			AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
			AND ((SCS.RepeatCount=@rRepeatCount)OR (@rRepeatCount=0))
			
             AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		    
		    
		    AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		    
		    AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')	
	        
	        AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
	        
	        AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
		    
		    AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
		            
		    AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		           
		    AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		           
		    AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		                   
		    AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		           
		    AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		     
		    AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')		
		    
		    AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		    
		    AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		    
		    AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		    
		    AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		    
		    AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		    
		    AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		    
		     -- AND (ISNULL(SCS.RepeatCount,1) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount=1)
		  
		    AND (ISNULL(SCS.StudentStatusId,'') IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatus,','))OR @rStudentStatus='')
		  
		 -- AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
			  
			--AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		  
		    AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		    AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0)) 
		    AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		    AND ((SCS.Code >= @rFromCode) OR (@rFromCode=''))
			AND ((SCS.Code <= @rToCode) OR (@rToCode=''))
			AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND ((SCS.MiddleName Like @rFatherName  + '%') OR (@rFatherName = ''))	 
			AND ((SCS.MotherName Like @rMotherName  + '%') OR (@rMotherName = ''))	 
			AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')	
			AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')			
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
		SET @sql=
		'SELECT 
				StudentId,
				Code AS Code,
				Name,
				ClassName1 AS ClassName,
				StatusName,
				ParentContactNo
		FROM sStudent.tTempStudent1 ORDER BY '+@rOrderBy

		exec(@Sql)
		 
		DROP Table sStudent.tTempStudent1
		DROP Table sStudent.tTempStudent2
		DROP Table sStudent.tTempStudent3
		DROP Table sStudent.tTempStudent4
		DROP Table sStudent.tTempStudent8
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
END
GO
PRINT N'Altering [sStudent].[pStudentDetailUpdate]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentDetailUpdate]
	 
	@rStudentId Bigint=0,
	@rCategory int,
	@rSubCategory nvarchar(20),
	@rStrXml nvarchar(max)=''
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
		 if @rCategory=1
		 BEGIN
			IF @rSubCategory='Present Address'
			BEGIN
				Update sStudent.tStudentCommunication
				Set
					PresentStreetOne=A.PresentStreetOne,
					PresentStreetTwo=A.PresentStreetTwo,
					PresentStreetThree=A.PresentStreetThree,
					PresentCountry=A.PresentCountry,
					PresentState=A.PresentState,
					PresentCity=A.PresentCity,
					PresentZipCode=A.PresentZipCode,
					PresentContactNo=A.PresentContactNo
				From
				(
					Select StudentId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,
					       PresentState,PresentCity,PresentZipCode,PresentContactNo
					from openxml (@loDoc,'/Table/Student',1)
					with
					(
						StudentId bigint,
						PresentStreetOne nvarchar(100),
						PresentStreetTwo nvarchar(100),
						PresentStreetThree nvarchar(100),
						PresentCountry nvarchar(50),
						PresentState nvarchar(50),
						PresentCity nvarchar(50),
						PresentZipCode nvarchar(50),
						PresentContactNo nvarchar(50)
					)	   
				)A Where sStudent.tStudentCommunication.StudentId=A.StudentId
			END
			IF @rSubCategory='Permanent Address'
			BEGIN
				Update sStudent.tStudentCommunication
				Set
					PermanentStreetOne=A.PresentStreetOne,
					PermanentStreetTwo=A.PresentStreetTwo,
					PermanentStreetThree=A.PresentStreetThree,
					PermanentCountry=A.PresentCountry,
					PermanentState=A.PresentState,
					PermanentCity=A.PresentCity,
					PermanentZipCode=A.PresentZipCode,
					PermanentContactNo=A.PresentContactNo
				from
				(
					Select StudentId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,
						    PresentState,PresentCity,PresentZipCode,PresentContactNo
					From openXml(@loDoc,'/Table/Student',1)
					With
					(
						StudentId bigint,
						PresentStreetOne nvarchar(150),
						PresentStreetTwo nvarchar(150),
						PresentStreetThree nvarchar(150),
						PresentCountry nvarchar(50),
						PresentState nvarchar(50),
						PresentCity nvarchar(50),
						PresentZipCode nvarchar(20),
						PresentContactNo nvarchar(20)
					)	
				)A Where sStudent.tStudentCommunication.StudentId=A.StudentId
			END
			IF @rSubCategory='Emergency Address'
			BEGIN
				Update sStudent.tStudentCommunication
				Set
					EmergencyStreetOne=A.PresentStreetOne,
					EmergencyStreetTwo=A.PresentStreetTwo,
					EmergencyStreetThree=A.PresentStreetThree,
					EmergencyCountry=A.PresentCountry,
					EmergencyState=A.PresentState,
					EmergencyCity=A.PresentCity,
					EmergencyZipCode=A.PresentZipCode,
					EmergencyContactNo=A.PresentContactNo
				From
				(
					Select StudentId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,
						    PresentState,PresentCity,PresentZipCode,PresentContactNo
					From Openxml(@loDoc,'Table/Student',1)
					With
					(
						StudentId Bigint,
						PresentStreetOne nvarchar(150),
						PresentStreetTwo nvarchar(150),
						PresentStreetThree nvarchar(150),
						PresentCountry nvarchar(20),
						PresentState nvarchar(20),
						PresentCity nvarchar(20),
						PresentZipCode nvarchar(20),
						PresentContactNo nvarchar(20) 
					)
				) A Where sStudent.tStudentCommunication.StudentId=A.StudentId
			END
		END
		If @rCategory=2
		BEGIN
			If @rSubCategory='Father'
			BEGIN
				Update sStudent.tStudentFamily
				Set
					FatherName=A.Name,
					FatherDateOfBirth=A.DateOfBirth,
					FatherOccupation=A.Occupation,
					FatherQualification=A.Qualification,
					FatherContactNo=A.ContactNo,
					FatherMail=A.Mail,
					FatherOfficeAddress=A.OfficeAddress,
					FatherIncome=A.Income
				From
				(
					Select StudentId,Name,DateOfBirth,Occupation,
							Qualification,ContactNo,Mail,OfficeAddress,Income
					from openxml(@loDoc,'Table/Student',1)
					with
					(
						StudentId bigint,
						Name nvarchar(100),
						DateOfBirth date,
						Occupation nvarchar(50),
						Qualification nvarchar(50),
						ContactNo nvarchar(50),
						Mail nvarchar(50),
						OfficeAddress nvarchar(50),
						Income int
					)
				)A Where sStudent.tStudentFamily.StudentId=A.StudentId
			END
			IF @rSubCategory='Mother'
			BEGIN
				update sStudent.tStudentFamily 
				Set
					MotherName=A.Name,
					MotherDateOfBirth=A.DateOfBirth,
					MotherOccupation=A.Occupation,
					MotherQualification=A.Qualification,
					MotherContactNo=A.ContactNo,
					MotherMail=A.Mail,
					MotherOfficeAddress=A.OfficeAddress,
					MotherIncome=A.Income
				from
				(
					Select StudentId,Name,DateOfBirth,Occupation,
							Qualification,ContactNo,Mail,OfficeAddress,Income
					
					from openxml(@loDoc,'Table/Student',1)
					With
					(
						StudentId bigint,
						Name nvarchar(100),
						DateOfBirth date,
						Occupation nvarchar(50),
						Qualification nvarchar(50),
						ContactNo nvarchar(20),
						Mail nvarchar(50),
						OfficeAddress nvarchar(50),
						Income int
					)
				)A Where sStudent.tStudentFamily.StudentId=A.StudentId
			END
			IF @rSubCategory ='Relative'
			BEGIN
				Update sStudent.tStudentFamily 
				Set 
					RelationshipName =A.RelationshipName,
					RelativeName=A.Name,
					RelativeDateOfBirth=A.DateOfBirth,
					RelativeOccupation=A.Occupation,
					RelativeQualification=A.Qualification,
					RelativeContactNo=A.ContactNo,
					RelativeMail=A.Mail,
					RelativeOfficeAddress=A.OfficeAddress,
					RelativeIncome=A.Income
				From
				(
					Select StudentId,RelationshipName,Name,DateOfBirth,Occupation,
							Qualification,ContactNo,Mail,OfficeAddress,Income
					From Openxml(@loDoc,'Table/Student',1)
						With
						(
							StudentId bigint,
							RelationshipName nvarchar(100),
							Name nvarchar(100),
							DateOfBirth date,
							Occupation nvarchar(50),
							Qualification nvarchar(50),
							ContactNo nvarchar(20),
							Mail nvarchar(50),
							OfficeAddress nvarchar(50),
							Income int
						)
				)A Where sStudent.tStudentFamily.StudentId=A.StudentId
			END
		END
		If @rCategory=3
		BEGIN
			DECLARE @Str varchar(500)=''
			IF @rSubCategory ='Academic'
			BEGIN
				Create Table #table1
				(
					FirstName nvarchar(100),
					MiddleName nvarchar(100),
					LastName nvarchar(100),
					StudentId bigint,
					AdmissionStandardId int,
					AdmissionDate date,
					GenderId int,
					DateOfBirth date
				)
				Insert into #table1
				Select FirstName,MiddleName,LastName,StudentId, AdmissionStandardId,AdmissionDate,GenderId,DateOfBirth
					From Openxml(@loDoc,'Table/Student',1)
						With
						( 
							FirstName nvarchar(100),
							MiddleName nvarchar(100),
							LastName nvarchar(100),
							StudentId bigint,
							AdmissionStandardId int,
							AdmissionDate date,
							GenderId int,
							DateOfBirth Date
						) 
			 IF Exists (SELECT 1 FROM #table1 WHERE AdmissionDate <= DateOfBirth)
			BEGIN
					--Set @Str=''
					--SELECT @Str=COALESCE(@Str,'')+CAST(FirstName As nvarchar(50))+ ',' FROM #table1 WHERE AdmissionDate >= DateOfBirth
					select -109,@Str AS Result
			RETURN		
			END 
			-- --Select * from #table1
				Update  Stu
				Set
					FirstName =T.FirstName,
					MiddleName=T.MiddleName,
					LastName=T.LastName 
					
				From sStudent.tStudentMaster Stu
				INNER JOIN #table1 T ON T.StudentId =Stu.Id
				Where Stu.Id =T.StudentId
					
				Update A
				Set 
						AdmissionDate=T.AdmissionDate,
						AdmissionStandardId =T.AdmissionStandardId
				from sStudent.tStudentAdmission A 
				INNER JOIN #table1 T ON T.StudentId =A.StudentId
				
				 
				
				Update SO 
				Set
					GenderId =T1.GenderId,
					
					DateOfBirth=T1.DateOfBirth
				From sStudent.tStudentOther SO 
				INNER JOIN #table1 T1 ON T1.StudentId=So.StudentId
				
				
				
				
				--Update sStudent.tStudentMaster
				--Set
				--	FirstName =SM.FirstName,
				--	MiddleName=SM.MiddleName,
				--	LastName=SM.LastName
					
				--From
				--(
				--	Select StudentId,FirstName,MiddleName,LastName
				--	From Openxml(@loDoc,'Table/Student',1)
				--		With
				--		(
				--			StudentId bigint,
				--			FirstName nvarchar(100),
				--			MiddleName nvarchar(100),
				--			LastName nvarchar(100)
				--		) 
				--)SM 
				--Where sStudent.tStudentMaster.Id=SM.StudentId
				
				 
				--Update sStudent.tAcademic
				--Set
				--	ClassID=AC.CLassId,
				--	DivisionId=AC.DivisionID
				--From
				--(
				--	Select StudentID,ClassID,DivisionId
				--	from OpenXml(@loDoc,'Table/Student',1)
				--	With
				--	(
				--		StudentID bigint,
				--		ClassID int,
				--		DivisionID int
				--	)
				--)AC Where sStudent.tAcademic.StudentId=AC.StudentID
				 
				--Update sStudent.tStudentAdmission
				--Set
				--	AdmissionStandardId =A.AdmissionStandardId,
				--	AdmissionDate =A.AdmissionDate
				--From
				--(
				--	Select StudentID,AdmissionStandardId,AdmissionDate
				--	from Openxml(@loDoc,'Table/Student',1)
				--	With
				--	(
				--		StudentID Bigint,
				--		AdmissionStandardId int,
				--		AdmissionDate date
				--	)
				--)A Where sStudent.tStudentAdmission.StudentId=A.StudentID
			 END
		END
		 	Select 1 As Result
END
GO
PRINT N'Altering [sStudent].[pStudentDetailUpdateGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentDetailUpdateGet]
	 
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rBatchId int,
	 --@rIsBlank bit,
	 @rStatusId int,
	 @rOrderBy int
	 
AS
SET NOCOUNT ON

BEGIN
	 	DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		 
		 
		 IF @rCategoryId=1 
		 BEGIN-- Communication
			IF @rSubCategory ='Present Address'
			BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						PresentStreetOne,
						PresentStreetTwo,
						PresentStreetThree,
						PresentCountry,
						PresentState,
						PresentCity,
						PresentZipCode,
						PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			IF @rSubCategory ='Permanent Address'
			BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						PermanentStreetOne As PresentStreetOne,
						PermanentStreetTwo AS PresentStreetTwo,
						PermanentStreetThree AS PresentStreetThree,
						PermanentCountry AS PresentCountry,
						PermanentState AS PresentState,
						PermanentCity As PresentCity,
						PermanentZipCode As PresentZipCode,
						PermanentContactNo AS PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			IF @rSubCategory ='Emergency Address'
			BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						EmergencyStreetOne AS PresentStreetOne,
						EmergencyStreetTwo As PresentStreetTwo, 
						EmergencyStreetThree As PresentStreetThree,
						EmergencyCountry As PresentCountry,
						EmergencyState As PresentState,
						EmergencyCity AS PresentCity,
						EmergencyZipCode As PresentZipCode,
						EmergencyContactNo  AS PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
		END
		IF @rCategoryId= 4 
		BEGIN --Family
			IF @rSubCategory ='Father'
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							FatherName,FatherDateOfBirth,FatherOccupation,FatherQualification,FatherContactNo,FatherMail,
							FatherOfficeAddress,FatherIncome
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			IF @rSubCategory ='Mother'
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							MotherName,MotherDateOfBirth,MotherOccupation,MotherQualification,MotherContactNo,MotherMail,
							MotherOfficeAddress,MotherIncome
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
					AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			IF @rSubCategory ='Relative'
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							RelativeName,RelativeDateOfBirth,RelativeOccupation,RelativeQualification,RelativeContactNo,RelativeMail,
							RelativeOfficeAddress,RelativeIncome,RelationshipName
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
					AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
			END
			
		END			
		IF @rCategoryId= 10 
		BEGIN
			IF @rSubCategory ='Academic'
			BEGIN
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,convert(date,SO.DateOfBirth) As DateOfBirth,AD.AdmissionDate,AD.AdmissionStandardId,SA.Name,Sa.RollNo,SO.GenderId
					From  
						 sStudent.vStudentAcademic SA
						INNER JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
						LEFT JOIN sStudent.tStudentAdmission AD
									ON AD.StudentID = SA.StudentId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,convert(date,SO.DateOfBirth) DateOfBirth,AD.AdmissionDate,AD.AdmissionStandardId,SA.Name,Sa.RollNo,SO.GenderId
					From  
						 sStudent.vStudentAcademic SA
						INNER JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
						LEFT JOIN sStudent.tStudentAdmission AD
									ON AD.StudentID = SA.StudentId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					Order by Code
				END
			END
		END
	 
		   
END
GO
PRINT N'Altering [sStudent].[pStudentGenerateReport]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentGenerateReport]
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9999-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9999-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount smallint=0,
	@rStudentStatusId smallint=0,
	@rHostelId nvarchar(max) = '',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption nvarchar(max)=''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate='0001-01-01'
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate='9999-12-31'
	IF(@rDOAFromDate IS NULL)
		SET @rDOAFromDate='0001-01-01'
	IF(@rDOAToDate IS NULL)
		SET @rDOAToDate='9999-12-31'
	IF(@rDOLFromDate IS NULL)
		SET @rDOLFromDate='0001-01-01'
	IF(@rDOLToDate IS NULL)
		SET @rDOLToDate='9999-12-31'
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sStudent.tStudentCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgId,
			Code,
			FirstName,	
			LastName,
			Country,
			State,
			City,
			Area,
			DivisionId,
			StatusId,
			TransportModeId,
			BusRouteDestinationId,
			BloodGroupId,
			GenderId,
			ReligionId,
			CastCategoryId,
			HouseId,
			MotherTongueId,
			NationalityId,
			Hobby,
			FatherQualification,
			MotherQualification,
			FatherOccupation,
			MotherOccupation,
			PreviousSchool,
			AdmissionCategoryId,
			DOBFromDate,
			DOBToDate,
			DOAFromDate,
			DOAToDate,
			DOLFromDate,
			DOLToDate,
			IsPysicalDeformity,
			IsMajorIllness,
			IsCommon,
			CreatedUserId,
			CreatedDateTime,
			IsBlackList,
			FromCode,
			ToCode,
			CustomTag,
			CustomGroup,
	        Club,
	        RepeatCount,
	        StudentStatusId,
	        Hostel,
	       FeeExemption
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rCountry,
			@rState,
			@rCity,
			@rArea,
			@rDivisionId,
			@rStatusId,
			@rTransportModeId,
			@rBusRouteDestinationId,
			@rBloodGroupId,
			@rGenderId,
			@rReligionId,
			@rCastCategoryId,
			@rHouseId,
			@rMotherTongueId,
			@rNationalityId,
			@rHobby,
			@rFatherQualification,
			@rMotherQualification,
			@rFatherOccupation,
			@rMotherOccupation,
			@rPreviousSchool,
			@rAdmissionCategoryId,
			@rDOBFromDate,
			@rDOBToDate,
			@rDOAFromDate,
			@rDOAToDate,
			@rDOLFromDate,
			@rDOLToDate,
			@rIsPysicalDeformity,
			@rIsMajorIllness,
			@rIsCommon,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsBlackList,
			@rFromCode,
			@rToCode,
			@rCustomTagId,
			@rCustomGroupId,
	        @rClubId,
			@rRepeatCount,
			@rStudentStatusId,
			@rHostelId,
			@rFeeExemption
			
		)
		--SELECT @lNextNumber AS Result
	END
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rCountry=Country,
				@rState=State,
				@rCity=City,
				@rArea=Area,
				@rDivisionId=DivisionId,
				@rStatusId=StatusId,
				@rTransportModeId=TransportModeId,
				@rBusRouteDestinationId=BusRouteDestinationId,
				@rBloodGroupId=BloodGroupId,
				@rGenderId=GenderId,
				@rReligionId=ReligionId,
				@rCastCategoryId=CastCategoryId,
				@rHouseId=HouseId,
				@rMotherTongueId=MotherTongueId,
				@rNationalityId=NationalityId,
				@rHobby=Hobby,
				@rFatherQualification=FatherQualification,
				@rMotherQualification=MotherQualification,
				@rFatherOccupation=FatherOccupation,
				@rMotherOccupation=MotherOccupation,
				@rPreviousSchool=PreviousSchool,
				@rAdmissionCategoryId=AdmissionCategoryId,
				@rDOBFromDate=DOBFromDate,
				@rDOBToDate=DOBToDate,
				@rDOAFromDate=DOAFromDate,
				@rDOAToDate=DOAToDate,
				@rDOLFromDate=DOLFromDate,
				@rDOLToDate=DOLToDate,
				@rIsPysicalDeformity=IsPysicalDeformity,
				@rIsMajorIllness=IsMajorIllness,
				@rIsBlackList=IsBlackList,
				@rFromCode=FromCode,
				@rToCode=ToCode,
				@rCustomTagId=CustomTag,
				@rCustomGroupId = CustomGroup,
	            @rClubId = Club,
	            @rRepeatCount = RepeatCount,
	            @rStudentStatusId =StudentStatusId,
	            @rHostelId = Hostel,
	           @rFeeExemption =FeeExemption
		FROM
			sStudent.tStudentCustomSearch
		WHERE
			Id=@rId
	END
	
	SET @rColumnName=Replace(@rColumnName,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	SET @rColumnName=Replace(@rColumnName,'PhysicalDeformityRemark','PysicalDeformityRemark')
	SET @rColumnName=Replace(@rColumnName,'IsPhysicalDeformity','IsPysicalDeformity')
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rCountry = sCommon.fSearchStringGet(@rCountry)
	SET @rState = sCommon.fSearchStringGet(@rState)
	--SET @rCity = sCommon.fSearchStringGet(@rCity)
	
		--IF (@rCustomTagId <> '')
		--BEGIN
		--	SELECT	
		--	DISTINCT SM.Id AS StudentId1
		--	INTO sStudent.tTempStudent3
		--	FROM sStudent.tStudentMaster SM
		--	INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
		--	INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		--	WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
		--	AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--END
		--ELSE
		--BEGIN
		--	SELECT 
		--	DISTINCT NULL AS StudentId1
		--	INTO sStudent.tTempStudent3
		--END
	
		-- For Custom Tag
		IF (@rCustomTagId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId1
			INTO sStudent.tTempStudent5
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId1
			INTO sStudent.tTempStudent5
		END
		
		-- For Custom Group
		IF (@rCustomGroupId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId2
			INTO sStudent.tTempStudent6
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId2
			INTO sStudent.tTempStudent6
		END
		
		-- For Club Group
		IF (@rClubId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId3
			INTO sStudent.tTempStudent7
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId3
			INTO sStudent.tTempStudent7
		END
		
		-- For Hostel
		IF (@rHostelId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId4
			INTO sStudent.tTempStudent9
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
			AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
			WHERE SM.OrgId = @rOrgId --AND A.BatchId = @BatchId 
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId4
			INTO sStudent.tTempStudent9
		END
	
	--Transport
		IF (@rBusRouteId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId5
			INTO sStudent.tTempStudent10
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
			AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE SM.OrgId = @rOrgId 
			AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId5
			INTO sStudent.tTempStudent10
		END
		
		 
		SELECT 
			* into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
	    INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
	   --INNER JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6 OR @rFeeExemption = ''
		WHERE 
			SCS.OrgId = @rOrgId AND SCS.BatchId = @BatchId 
			AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
			AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%')OR(@rCountry = ''))
			AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
			--AND ((ISNULL(SCS.PermanentCity,'') Like @rCity + '%')OR(@rCity = ''))
			AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
			AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
			AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
			AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
			AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
			AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
				
			--AND (SCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    
		    AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		    
		    AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		    
		    AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')	
	        
	        AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
	        
	        AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
		    
		    AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
		            
		    AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		           
		    AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		           
		    AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		                   
		    AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		           
		    AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		     
		    AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')		
		    
		    AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		    
		    AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		    
		    AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		    
		    AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
			
		    AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		    
			AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		
			AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
			
			AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
			
			AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		    AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0)) 
		    AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		    AND ((SCS.Code >= @rFromCode) OR (@rFromCode=0))
		    AND ((SCS.Code <= @rToCode) OR (@rToCode=0))
			AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')		
			 AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')		
		SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [ID No]')
		--SET @rColumnName=Replace(@rColumnName,',UIDNumber',','  +'&#39;+UIDNumber AS UIDNumber')
		--SET @rColumnName=Replace(@rColumnName,',UIDNumber',',' + '''''''''' +'+UIDNumber AS UIDNumber')
		 
			--select @rColumnName
		
		
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		exec(@Sql)
		
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10


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


GO

ALTER PROCEDURE [sStudent].[pUserControlStudentSearchGet]
	 
	@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 = 0,
	@rOrgGroupBatchId int = 0,
	@rSUId nvarchar(20)=''
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
		BEGIN
			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.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.BatchId,
			SA.SUId,
			ISNULL(So.GenderId,0) AS GenderId
  FROM 
          sStudent.vStudentAcademic SA
           LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@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 OR @rOrgId = 0)
		AND ( OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId ,
			SA.SUId,
			ISNULL(So.GenderId,0) AS GenderId
  FROM 
          sStudent.vStudentAcademic SA    
           LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId         
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@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) OR (@rOrgId=0))
			AND ( OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND(SA.BatchId=@rBatchId)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = '')) 	

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


GO
 
ALTER PROC [sSystem].[pDBBackupInRAR] 

@DBName varchar(150),
@BackupPath varchar(250)
as

declare @Sdate varchar(250)
DECLARE @SERVER VARCHAR(200), @COMMAND VARCHAR(200), @FILE VARCHAR(200)

set @Sdate= replace(convert(varchar,GETDATE(),103),'/','')+ replace(convert(varchar(5),GETDATE(),108),':','') +'_' + RIGHT(@DBName,9) + '.BAK'
set @FILE= replace(convert(varchar,GETDATE(),103),'/','')+ replace(convert(varchar(5),GETDATE(),108),':','') +'_'+ RIGHT(@DBName,9) + '.RAR'

set @Sdate =@BackupPath + @Sdate


BACKUP DATABASE @DBName

TO DISK = @Sdate
   WITH FORMAT
PRINT @Sdate + ' Backup file is ready'
 

SET @COMMAND =  @BackupPath + '\RAR.exe a ' + @BackupPath  + @FILE + ' ' + @Sdate
print @COMMAND
EXEC master..XP_CMDSHELL @COMMAND
PRINT @FILE + ': Backup file is COMPRESSED'


SET @COMMAND ='DEL '+ @Sdate
EXEC master..XP_CMDSHELL @COMMAND 
PRINT 'Delete temporary file'
PRINT 'Download Compressed Backup file '+ @file

EXEC [sSystem].[pBackupLogAdd] @BackupPath
GO
PRINT N'Altering [sTimetable].[pImportTeacherToAcademicAdd]...';


GO
 
ALTER PROCEDURE [sTimetable].[pImportTeacherToAcademicAdd]
	 
	@rOrgId int,
	@rEmployeeId bigint=0,
	@rSubjectId int,
	@rDivisionId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
BEGIN
	  if NOT Exists(Select 1 from sAcademic.tTeacherSubjectDivision TV 
	  INNER JOIN sTimetable.tTeacherWorkLoad T on T.DivisionId = TV.DivisionId AND T.EMployeeId = Tv.EmployeeId 
	  INNER JOIN  sHrm.tEmployeeMaster  EMp ON EMp.Id=TV.EmployeeId  where EMp.OrgId=@rOrgId ANd TV.EmployeeId=@rEmployeeId
	  AND TV.subjectid=@rSubjectId AND Tv.DivisionId=@rDivisionId)
	BEGIN
		 
		--update TV  Set TV.DivisionId=TW.DivisionId,TV.SubjectId =Tw.SubjectId,TV.EmployeeId = Tw.EmployeeID  
		--from sAcademic.tTeacherSubjectDivision TV 
		--INNER JOIN sTimetable.tTeacherWorkLoad TW ON Tw.DivisionId = TV.DivisionId AND TW.EmployeeId = TV.EmployeeID  
		--INNER JOIN  sHrm.tEmployeeMaster  EMp ON EMp.Id=TV.EmployeeId
		--where EMp.OrgId=@rOrgId  ANd TV.EmployeeId=@rEmployeeId 
				  
		Insert into sAcademic.tTeacherSubjectDivision
		(
			DivisionId,
			SubjectId,
			EmployeeId
		)
		Values
		(	
			@rDivisionId,
			@rSubjectId,
			@rEmployeeId  
		)
		
		if NOT exists(select 1 from sAcademic.tTeacherSubject T
		INNER JOIN sAcademic.tTeacherSubjectDivision TV ON TV.SubjectId = T.SubjectId AND T.EmployeeId = TV.EmployeeID  
		INNER JOIN  sTimetable.tTeacherWorkLoad  TW ON Tw.DivisionId = TV.DivisionId AND TW.EmployeeId = TV.EmployeeID 
		WHere  TV.EmployeeId=@rEmployeeId AND TV.subjectid=@rSubjectId AND Tv.DivisionId=@rDivisionId)
		BEGIN
			Insert INto sAcademic.tTeacherSubject 
			(
				EmployeeId,
				SubjectId
			)
			Values
			(
				@rEmployeeId,
				@rSubjectId
			)
		END
		--else
		--BEGIN
		--	Insert INto sAcademic.tTeacherSubject 
		--	(
		--		EmployeeId,
		--		SubjectId
		--	)
		--	SELECT TV.EmployeeId,TV.SubjectId FROM sAcademic.tTeacherSubjectDivision TV
		--	INNER JOIN  sTimetable.tTeacherWorkLoad  TW ON Tw.DivisionId = TV.DivisionId AND TW.EmployeeId = TV.EmployeeID
		--	WHERE TV.EmployeeId=@rEmployeeId 
		--END
		
	END
--	Else
--	BEGIN
--	 INSERT INTO sAcademic.tTeacherSubjectDivision
--		(
--			EmployeeId,
--			DivisionId,
--			SubjectId 
		 
--			)
		 
--		 Select Tw.EmployeeId,Tw.DivisionId,Tw.SubjectId from sTimetable.tTeacherWorkLoad TW INNER JOIN sSetup.tDivisionMaster EM ON EM.Id= TW.DivisionId
--		 Where EM.OrgID =@rOrgId  ANd TW.EmployeeId=@rEmployeeId
--		 if exists(select 1 from sAcademic.tTeacherSubject T
--		INNER JOIN sAcademic.tTeacherSubjectDivision TV ON TV.SubjectId = T.SubjectId AND T.EmployeeId = TV.EmployeeID  
--		INNER JOIN  sTimetable.tTeacherWorkLoad  TW ON Tw.DivisionId = TV.DivisionId AND TW.EmployeeId = TV.EmployeeID 
--		WHere  TV.EmployeeId=@rEmployeeId )
--		BEGIN
--			Update T Set T.SubjectId=TV.SubjectId,T.EmployeeId=@rEmployeeId
--			From sAcademic.tTeacherSubject  T 
--			INNER JOIN sAcademic.tTeacherSubjectDivision TV ON TV.SubjectId = T.SubjectId AND T.EmployeeId = TV.EmployeeID  
--			INNER JOIN  sTimetable.tTeacherWorkLoad  TW ON Tw.DivisionId = TV.DivisionId AND TW.EmployeeId = TV.EmployeeID  
--			 Where  TV.EmployeeId=@rEmployeeId
--		END
--		else
--		BEGIN
--			Insert INto sAcademic.tTeacherSubject 
--			(
--				EmployeeId,
--				SubjectId
--			)
--			SELECT TV.EmployeeId,TV.SubjectId FROM sAcademic.tTeacherSubjectDivision TV
--			INNER JOIN  sTimetable.tTeacherWorkLoad  TW ON Tw.DivisionId = TV.DivisionId AND TW.EmployeeId = TV.EmployeeID
--			WHERE TV.EmployeeId=@rEmployeeId 
--		END
		
        
--END
 SELECT 1 AS Result
END
GO
PRINT N'Altering [sTool].[pDeleteStaticData]...';


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

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


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

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

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

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


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

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

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

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

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

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

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

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

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

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

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

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

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

DELETE FROM sSystem.tStaticVersion

DELETE FROM sCommunication.tFeedBackAnswerGroupMaster

END
GO
PRINT N'Altering [sTransport].[pRptAssignRouteGet]...';


GO

ALTER PROCEDURE [sTransport].[pRptAssignRouteGet]
           @rTransportId int =0,
           @rBusRouteId int,
           @rOrgGroupBatchId int,
           @rOrgId smallint,
           @rPickuppoint int
AS
SET NOCOUNT ON
			
BEGIN
declare @string nvarchar(max)
SELECT 
		   BRM.Title as BusRoute,
		   ISnull(BRDM.Title,'') as PickupPoint,
		   BRM.OrderIndex AS RouteOrder,
		   BRDM.OrderIndex AS PickupOrder,
		   BRM.Id AS BusRouteId,
		   VA.OrgId AS OrgId,
		   VA.OrganizationName  AS OrganizationName,
		   BRDM.Id AS PickupDestinationId,
		  [sTransport].[fAssignRouteCodeGet](@rTransportId,BRDM.Id,VA.OrgId,@rOrgGroupBatchId) AS Code
		FROM
		sTransport.tAssignRoute AR
		INNER JOIN sStudent.vStudentLastAcademic VA  ON AR.SourceId=VA.StudentId AND AR.SourceTypeId=2003
		LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
		LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND BRM.OrgGroupBatchId=@rOrgGroupBatchId
  WHERE 
	 BRM.TransportId = @rTransportId
	 And BRM.IsObsolete=0
	 AND ((VA.OrgId=@rOrgId) OR (@rOrgId=0))
	 AND ((BRDM.BusRouteId=@rBusRouteId)OR (@rBusRouteId=0) )
	 AND VA.OrgGroupBatchId=@rOrgGroupBatchId
	  AND ((BRDM.Id=@rPickuppoint) OR (@rPickuppoint=0))
   
END
GO
PRINT N'Altering [sTransport].[pRptBlankPrintRouteGet]...';


GO

ALTER PROCEDURE [sTransport].[pRptBlankPrintRouteGet]
           @rTransportId int =0,
           @rBusRouteId int,
           @rOrgGroupBatchId int,
           @rPickuppoint int
AS
SET NOCOUNT ON
			
BEGIN
SELECT 
		   ISNULL(BRM.RouteNumber,0) AS RouteNumber,
		   BRM.Title as BusRoute,
		   ISNULL(BRM.Id,0)AS BusRouteId,
		   ISnull(BRDM.Title,'') as PickupPoint,
		    BRM.OrderIndex
		FROM
		   sTransport.tBusRouteMaster BRM
		   INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.BusRouteId=BRM.Id
  WHERE 
	 BRM.TransportId = @rTransportId
	 AND BRM.IsObsolete=0
	 AND ((BRM.Id=@rBusRouteId )OR(@rBusRouteId=0))
	 AND BRM.OrgGroupBatchId=@rOrgGroupBatchId
	  AND ((BRDM.Id=@rPickuppoint) OR (@rPickuppoint=0))
    --order by BRM.OrderIndex
END
GO
PRINT N'Creating [sBiometric].[pEmployeeCheckOutGet]...';


GO

CREATE PROCEDURE [sBiometric].[pEmployeeCheckOutGet]
	 
	 @rOrgId int,
	 @rEmployeeId bigint=0,
	 @rId bigint=0
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 Select 
		U.LoginTitle,B.EmployeePhoto ,EMp.FirstName+' ' +EMp.MiddleName+' '+emp.LastName AS Name,B.CheckInTime,Emp.Id As EmployeeID ,B.CheckOutTime,B.Id
	 from sSecurity.tUser 
	 U INNER JOIN sHrm.tEmployeeMaster EMP ON  EMP.Id=U.SourceId
	 INNER JOIN sBiometric.tEmployeeCheckIn B ON B.EmployeeID=EMP.Id
	 WHere U.SourceTypeId =95 AND U.OrgId=@rORgId AND  ((B.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
	 AND B.Id=@rId
	
END
GO
PRINT N'Creating [sBiometric].[pLateTimeSheetListGet]...';


GO
CREATE PROCEDURE [sBiometric].[pLateTimeSheetListGet]
	 @rEmployeeId bigint=0,
	 @rFromDate Date,
	 @rToDate Date,
	 @rStatus nvarchar(10) = '0'

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	CREATE TABLE #TempMonthTrans
	(
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20)
	)
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	SELECT 
	TM.*,
	MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,
	Tot_Abs AS TotalAbsent,
	Tot_WeekOff AS TotalWeekOff,
	Tot_Holiday AS Totalholiday,
	Tot_Leave AS TotalLeave,
	EM.FirstName + ' ' + EM.LastName AS Name,
	EM.Code,
	ISNULL(ELS.Id,0) AS EmployeeLateStatusId
	FROM #TempMonthTrans TM 
	INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId
	INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId
	LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)
	WHERE 
	TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate 	
	AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
	AND (PresentStatus = @rStatus OR @rStatus='0') AND PresentStatus IN ('LH','HD')
	Order By TM.EmployeeId,TM.Attn_Date
END
GO
PRINT N'Creating [sBiometric].[pMonthlyPresenceSummaryGet]...';


GO
CREATE PROCEDURE [sBiometric].[pMonthlyPresenceSummaryGet]
	 
	 @rCode nvarchar(20)='',
	 @rForYear int,
	 @rForMonth int,
	 @rOrgId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	DECLARE @lAttendanceDate AS nvarchar(20)
	SET @lAttendanceDate = CONVERT(nvarchar(10), @rForYear) + '-' + CONVERT(nvarchar(10), @rForMonth) + '-' + '01'

	DECLARE @lOrgGroupId int=0
	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
		
	DECLARE @lItemValue nvarchar(20) = ''
	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 204

	SELECT
		ROW_NUMBER() OVER (ORDER BY EM.Id ASC) AS SrNo,
		EM.Code,
		EM.FirstName + ' ' + EM.Lastname AS Name,
		Tot_Abs AS Absent,
		Count_Late AS Late,
		
		ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
		UNPIVOT
		(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
		WHERE convert(float,replace(value,':','.')) >= Convert(float,replace(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS DinnerAllowance,

		ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
		UNPIVOT
		(value FOR col IN (d01, d02, d03, d04, d05, d06, d07, d08, d09, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19, d20, d21, d22, d23, d24, d25, d26, d27, d28, d29, d30, d31)) PT
		WHERE value LIKE 'PW' AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS CompOff,
		
		convert(float,replace(Tot_Early,':','.')) + 
		ISNULL((SELECT SUM(convert(float,replace(value,':','.'))) FROM sBiometric.tMonthTrans
		UNPIVOT
		(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
		WHERE convert(float,replace(value,':','.')) >= Convert(float,replace('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS EarlyLeave,
		
		convert(float,replace(Tot_OT,':','.')) AS Tot_OT,
		
		(ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
		UNPIVOT
		(value FOR col IN (d01, d02, d03, d04, d05, d06, d07, d08, d09, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19, d20, d21, d22, d23, d24, d25, d26, d27, d28, d29, d30, d31)) PT
		WHERE value LIKE 'A' AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0))-
		(SELECT ISNULL(SUM(NoOfLeave),0) FROM sHrm.tLeave WHERE EmployeeId = 1001000000153 AND StatusId=550 AND FromDate BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))) AS LWP
		
	FROM 
		sBiometric.tMonthTrans MT
		INNER JOIN sHrm.tEmployeeMaster EM ON MT.EMployeeId = EM.Id AND MT.attn_dt = @lAttendanceDate
	WHERE (EM.Code = @rCode OR ISNULL(@rCode,'') = '')
END
GO
PRINT N'Creating [sCommunication].[pFeedbackAdd]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackAdd]
	 
	 	@rOrgGroupBatchId  int,
        @rId bigint=0,
        @rTitle nvarchar(200), 
		@rCreatedUserId bigint ,
		@rIsPublish bit,
		@rIsClose bit,
		@rFeedbackTemplateId bigint ,
		@rOrgGroupId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 DECLARE @lNextNumber BIGINT 

	 
	
	IF(@rId = 0)	
	BEGIN
		if exists(Select 1 from sCommunication.tFeedback where Title=@rTitle AND FeedbackTemplateId=@rFeedbackTemplateId)
	BEGIn
		Select -101 As Result
		Return
	END 
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedback', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tFeedback
		(
			Id,
			Title,
			FeedbackTemplateId ,
			IsPublish,
			IsClose,			
			OrgGroupBatchId,
			CreatedUserId,
			CreatedDateTime 
			 
		)
	VALUES
		(
			@lNextNumber,
			@rTitle, 
			@rFeedbackTemplateId,
			@rIsPublish,
			@rIsClose,
			@rOrgGroupBatchId,
			@rCreatedUserId,
			sCommon.fGetDate() 
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	    UPDATE  sCommunication.tFeedback
	    SET
			 
			Title=@rTitle, 
			FeedbackTemplateId=@rFeedbackTemplateId,
			IsPublish=@rIsPublish,
			IsClose=@rIsClose,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	 END  	

 
		
END
GO
PRINT N'Creating [sCommunication].[pFeedbackAnswerTemplateQuestionGet]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackAnswerTemplateQuestionGet]
	  
        @rFeedbackTemplateId bigint=0,
        @rId bigint=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		Id,
		QuestionNumber,
		Question ,
		FeedbackTemplateId,
		FeedbackAnswerTypeId ,
		CreatedUserId,
		 CreatedDateTime
		
	from sCommunication.tFeedbackTemplateQuestion
	Where  ((FeedbackTemplateId=@rFeedbackTemplateId) OR (@rFeedbackTemplateId=0))
	AND ((Id=@rId) OR (@rId=0))
	 
END
GO
PRINT N'Creating [sCommunication].[pFeedbackAnswerTypeDetailAdd]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackAnswerTypeDetailAdd]
	 
	 	 
         
        @rTitle nvarchar(200),
        @rFeedbackAnswerTypeId bigint,
        @rOrgGroupId int,
        @rIsDelete bit,
        @rFeedbackAnswerTypeDetailId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	  
	 IF (@rFeedbackAnswerTypeDetailId=0)
	 BEGIN
	 Declare @lNextNumber bigint
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackAnswerTypeDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	 
	 INSERT INTO sCommunication.tFeedbackAnswerTypeDetail
	 (
		Id,
		FeedbackAnswerTypeId,
		Title
	 )
	 Values
	 (
		@lNextNumber,
		@rFeedbackAnswerTypeId,
		@rTitle
	 )
	  
	 END
	 ELse 
	 BEGIN
	 SET @lNextNumber = @rFeedbackAnswerTypeDetailId
	 IF(@rIsDelete = 0)
	 BEGIN
	 UPDATE sCommunication.tFeedbackAnswerTypeDetail
	 SET
		Title=@rTitle,
		FeedbackAnswerTypeId=@rFeedbackAnswerTypeId
		WHERE Id=@rFeedbackAnswerTypeDetailId
	 END
	 ELSE 
		DELETE FROM sCommunication.tFeedbackAnswerTypeDetail  WHERE Id =  @rFeedbackAnswerTypeDetailId	
	END
	Select 1 As Result
END
GO
PRINT N'Creating [sCommunication].[pFeedbackAnswerTypeDetailGet]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackAnswerTypeDetailGet]
	  
        @rFeedbackAnswerTypeId bigint=0 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		Id,
		Title,
		FeedbackAnswerTypeId 
		 
		
	from sCommunication.tFeedbackAnswerTypeDetail 
	Where  FeedbackAnswerTypeId=@rFeedbackAnswerTypeId 
	 
END
GO
PRINT N'Creating [sCommunication].[pFeedbackAnswerTypeMasterAdd]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackAnswerTypeMasterAdd]
	 
	 	@rOrgGroupId smallint,
        @rId bigint=0,
        @rCode nvarchar(200),
        @rTitle nvarchar(200),
        @rIsObsolete bit,
		@rCreatedUserId bigint,
		@rFeedBackAnswerGroupMasterId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 DECLARE @lNextNumber BIGINT 

 
	
	
	IF(@rId = 0)	
	BEGIN
		
			if exists(Select 1 from sCommunication.tFeedbackAnswerTypeMaster where Code=@rCode)
	BEGIn
		Select -101 As Result
		Return
	END
	
	If exists(Select 1 from sCommunication.tFeedbackAnswerTypeMaster where Title =@rTitle)
	BEGIN
		Select -102 As Result
		Return
	END
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackAnswerTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tFeedbackAnswerTypeMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			OrgGroupId,
			CreatedUserId,
			CreatedDateTime,
			FeedBackAnswerGroupMasterId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rOrgGroupId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rFeedBackAnswerGroupMasterId
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	    UPDATE  sCommunication.tFeedbackAnswerTypeMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			OrgGroupId=@rOrgGroupId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() ,
			 FeedBackAnswerGroupMasterId=@rFeedBackAnswerGroupMasterId
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	 END  	

	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sCommunication].[pFeedbackAnswerTypeMasterGet]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackAnswerTypeMasterGet]
	 
	 	 
        @rCode nvarchar(200),
        @rTitle nvarchar(200),
        @rId bigint=0,
        @rOrgGroupId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		FT.Id,
		FT.Code,
		FT.Title,
		FT.IsObsolete,
		CreatedUserId,
		CreatedDateTime,
		FeedBackAnswerGroupMasterId,
		AG.Title As FeedBackAnswerGroupMaster
		
	from sCommunication.tFeedbackAnswerTypeMaster FT
	INNER JOIN sCommunication.tFeedBackAnswerGroupMaster AG ON Ag.Id =FT.FeedBackAnswerGroupMasterId
	Where ((FT.Code=@rCode) OR (ISNULL(@rCode,'')=''))
	AND ((FT.Title=@rTitle) OR (ISNULL(@rTitle,'')=''))
	AND ((FT.Id=@rId) OR (@rId=0))
	AND OrgGroupId=@rOrgGroupId
		
END
GO
PRINT N'Creating [sCommunication].[pFeedbackAssignAdd]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackAssignAdd]
	 
	 	 
        @rId bigint=0,
        @rAssignSourceTypeId smallint, 
		@rAssignSourceId bigint ,
		@rFeedbackId bigint,
		@rForName nvarchar(200) ,
		@rIsDelete bit
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rId=0)
	 BEGIN
	 Declare @lNextNumber bigint
	 
	 INSERT INTO sCommunication.tFeedbackAssign
	 (
		 
		AssignToSourceTypeId,
		AssignToSourceId,
		FeedbackId,
		ForName
	 )
	 Values
	 (
		 
		@rAssignSourceTypeId,
		@rAssignSourceId,
		@rFeedbackId,
		@rForName
	 )
	  
	 END
	 ELse 
	 BEGIN
	 SET @lNextNumber = @rId
	 IF(@rIsDelete = 0)
	 BEGIN
		 UPDATE sCommunication.tFeedbackAssign
		 SET
			AssignToSourceTypeId=@rAssignSourceTypeId,
			AssignToSourceId=@rAssignSourceId,
			FeedbackId=@rFeedbackId,
			ForName=@rForName
			WHERE Id=@rId
		 END 
		  ELSE 
		DELETE FROM sCommunication.tFeedbackAssign  WHERE Id =  @rId	
	END
		Select 1 As Result
END
GO
PRINT N'Creating [sCommunication].[pFeedbackAssignGet]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackAssignGet]
	  
        @rFeedbackId bigint=0,
        @rId bigint=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
		 (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			 FirstName +' ' + MiddleName+' ' + LastName
			From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95)
		 WHEN  2003
		 THEN
			(Select
			 FirstName +' ' + MiddleName+' ' + LastName
			From sStudent.tStudentMaster Where Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2003)
		 Else
			ForName
		 END) AS Name,
		FB.Id,
		AssignToSourceTypeId,
		AssignToSourceId,
		FeedbackId,
		ForName 
	  
		
	from sCommunication.tFeedbackAssign FB
	 
	Where  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))
	AND ((FB.Id=@rId) OR (@rId=0))
	 
END
GO
PRINT N'Creating [sCommunication].[pFeedbackForAdd]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackForAdd]
	 
	 	 
        @rId bigint=0,
        @rForSourceTypeId smallint, 
		@rForSourceId bigint ,
		@rFeedbackId bigint,
		@rForName nvarchar(200),
		@rOrgGroupId int=0,
		@rIsDelete bit
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rId=0)
	 BEGIN
	 Declare @lNextNumber bigint
	 
	 INSERT INTO sCommunication.tFeedbackFor
	 (
		 
		ForSourceTypeId,
		ForSourceId,
		FeedbackId,
		ForName
	 )
	 Values
	 (
		 
		@rForSourceTypeId,
		@rForSourceId,
		@rFeedbackId,
		@rForName
	 )
	  
	 END
	 ELse 
	 BEGIN
	 SET @lNextNumber = @rId
	 IF(@rIsDelete = 0)
	 BEGIN
		 UPDATE sCommunication.tFeedbackFor
		 SET
			ForSourceTypeId=@rForSourceTypeId,
			ForSourceId=@rForSourceId,
			FeedbackId=@rFeedbackId,
			ForName=@rForName
			WHERE Id=@rId
		 END 
		  ELSE 
		DELETE FROM sCommunication.tFeedbackFor WHERE Id =  @rId	
	 
		 END
		Select 1 As Result
END
GO
PRINT N'Creating [sCommunication].[pFeedbackForDelete]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackForDelete]
	    
        @rId bigint=0,
		@rOrgGroupbatchId bigint=0 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Delete from sCommunication.tFeedback where OrgGroupBatchId=@rOrgGroupbatchId ANd Id =@rId
	Delete from sCommunication.tFeedbackFor Where FeedbackId=@rId
	Delete from sCommunication.tFeedbackAssign Where FeedbackId=@rId
	Select 1 As Result
END
GO
PRINT N'Creating [sCommunication].[pFeedbackForGet]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackForGet]
	  
        @rFeedbackId bigint=0,
        @rId bigint=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
		 (CASE ForSourceTypeId WHen  95
		 THEN
			(Select 
			 FirstName +' ' + MiddleName+' ' + LastName
			From sHrm.tEmployeeMaster Where  Id=FB.ForSourceId And FB.ForSourceTypeId=95)
		 WHEN  2003
		 THEN
			(Select
			 FirstName +' ' + MiddleName+' ' + LastName
			From sStudent.tStudentMaster Where Id=FB.ForSourceId ANd FB.ForSourceTypeId=2003)
		 Else
			ForName
		 END) AS Name,
		FB.Id,
		ForSourceTypeId,
		ForSourceId,
		FeedbackId,
		ForName
		
	from sCommunication.tFeedbackFor FB
	 
	 
	Where  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))
	AND ((FB.Id=@rId) OR (@rId=0))
	 
END
GO
PRINT N'Creating [sCommunication].[pFeedbackGet]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackGet]
	 
	 	 
        
        @rTitle nvarchar(200),
        @rId bigint=0,
        @rOrgGroupBatchId int,
        @rFeedbackTemplateId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		 Id,
		 Title,
		 FeedbackTemplateId, 
		 IsPublish,
		IsClose,
		OrgGroupBatchId,
		CreatedUserId
		
	from sCommunication.tFeedback
	Where  
	(( Title=@rTitle) OR (ISNULL(@rTitle,'')=''))
	AND (( Id=@rId) OR (@rId=0))
	AND OrgGroupBatchId=@rOrgGroupBatchId
	AND ((FeedbackTemplateId=@rFeedbackTemplateId) OR (@rFeedbackTemplateId=0))
		
END
GO
PRINT N'Creating [sCommunication].[pFeedbackQuestionResponseAdd]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackQuestionResponseAdd]
	  
        @rFeedbackResponseId bigint=0,
        @rFeedbackTemplateQuestionId bigint,
        @rFeedbackAnswerTypeDetailId bigint,
        @rFeedbackAnswerDescription nvarchar(200)
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	 Insert Into sCommunication.tFeedbackQuestionResponse
	 (
		FeedbackResponseId,
		FeedbackTemplateQuestionId,
		FeedbackAnswerTypeDetailId,
		FeedbackAnswerDescription 
		 
	 )
	 Values
	 (
		@rFeedbackResponseId,
		@rFeedbackTemplateQuestionId,
		@rFeedbackAnswerTypeDetailId,
		@rFeedbackAnswerDescription 
		 
	 )
	 
END
GO
PRINT N'Creating [sCommunication].[pFeedbackResponseAdd]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackResponseAdd]
	  
        @rFeedbackId bigint=0,
        @rSourceTypeId smallint,
        @rSourceId bigint,
        @rCreatedUserId bigint,
        @rOrgGroupId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	  Declare @lNextNumber bigint 
	  EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackResponse', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	 Insert Into sCommunication.tFeedbackResponse
	 (
		Id,
		FeedbackId,
		SourceTypeId,
		SourceId,
		CreatedUserId,
		CreatedDateTime
	 )
	 Values
	 (
		@lNextNumber,
		@rFeedbackId,
		@rSourceTypeId,
		@rSourceId,
		@rCreatedUserId,
		sCommon.fGetDate() 
	 )
	Select @lNextNumber As Result
	 
END
GO
PRINT N'Creating [sCommunication].[pFeedbackResponseGet]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackResponseGet]
	 
	 
	 
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int ,
	 @rOrgGroupBatchId int,
	 @rOrgGroupId smallint
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	 
	if @rUserSourceTypeId   = 95 AND @rUserSourceTypeId   = 2003 
	
	BEGIN
	Select 
			 
			FT.Id As TempateQuestionId,
			FT.QuestionNumber,
			FT.Question 
	  From  sCommunication.tFeedbackTemplateQuestion FT
	  INNER JOIN sCommunication.tFeedbackAnswerTypeMaster AT ON AT.Id=FT.FeedbackAnswerTypeId
      INNER JOIN sCommunication.tFeedbackTemplate TM ON TM.Id=FT.FeedbackTemplateId ANd AT.OrgGroupId=@rOrgGroupId
      INNER JOIN sCommunication.tFeedback FB ON FB.FeedbackTemplateId=TM.Id  AND OrgGroupBatchId=@rOrgGroupBatchId
      INNER JOIN sCommunication.tFeedbackAssign FBGN on FBGN.FeedbackId=FB.Id
      Where 
		AssignToSourceId=@rUserSourceId
		
 END
  
 ELSE
 BEGIN
 
 Select 
			 
			FT.Id As TempateQuestionId,
			FT.QuestionNumber,
			FT.Question 
	  From  sCommunication.tFeedbackTemplateQuestion FT
	  INNER JOIN sCommunication.tFeedbackAnswerTypeMaster AT ON AT.Id=FT.FeedbackAnswerTypeId
      INNER JOIN sCommunication.tFeedbackTemplate TM ON TM.Id=FT.FeedbackTemplateId ANd AT.OrgGroupId=@rOrgGroupId
       
 
 
 END
 END
GO
PRINT N'Creating [sCommunication].[pFeedbackTemplateAdd]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackTemplateAdd]
	 
	 	@rOrgGroupId smallint,
        @rId bigint=0,
        @rCode nvarchar(200),
        @rTitle nvarchar(200), 
		@rCreatedUserId bigint 
		 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 DECLARE @lNextNumber BIGINT 

	 
	
	IF(@rId = 0)	
	BEGIN
		if exists(Select 1 from sCommunication.tFeedbackTemplate where Code=@rCode)
	BEGIn
		Select -101 As Result
		Return
	END
	
	If exists(Select 1 from sCommunication.tFeedbackTemplate where Title =@rTitle)
	BEGIN
		Select -102 As Result
		Return
	END
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackTemplate', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tFeedbackTemplate
		(
			Id,
			Code,
			Title, 
			OrgGroupId,
			CreatedUserId,
			CreatedDateTime 
			 
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle, 
			@rOrgGroupId,
			@rCreatedUserId,
			sCommon.fGetDate() 
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	    UPDATE  sCommunication.tFeedbackTemplate
	    SET
			Code=@rCode,
			Title=@rTitle, 
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	 END  	

	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sCommunication].[pFeedbackTemplateGet]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackTemplateGet]
	 
	 	 
        @rCode nvarchar(200),
        @rTitle nvarchar(200),
        @rId bigint=0,
        @rOrgGroupId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		 Id,
		 Code,
		 Title, 
		 OrgGroupId,
		CreatedUserId,
		CreatedDateTime 
		
	from sCommunication.tFeedbackTemplate  
	Where (( Code=@rCode) OR (ISNULL(@rCode,'')=''))
	AND (( Title=@rTitle) OR (ISNULL(@rTitle,'')=''))
	AND (( Id=@rId) OR (@rId=0))
	AND OrgGroupId=@rOrgGroupId
		
END
GO
PRINT N'Creating [sCommunication].[pFeedbackTemplateQuestionAdd]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackTemplateQuestionAdd]
	 
	 	 
         
         
        @rQuestionNumber  int,
        @rQuestion nvarchar(200),
        @rFeedbackTemplateId bigint,
        @rFeedbackAnswerTypeId bigint,
		@rCreatedUserId bigint,
		@rFeedbackTemplateQuestionId bigint,
		@rOrgGroupId int,
		@rIsDelete bit
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	  
	 IF (@rFeedbackTemplateQuestionId=0)
	 BEGIN
	 Declare @lNextNumber bigint
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackTemplateQuestion', 0, 1, 1,@outNextNumber = @lNextNumber output
	 
	 INSERT INTO sCommunication.tFeedbackTemplateQuestion
	 (
		Id,
		QuestionNumber,
		Question,
		FeedbackTemplateId,
		FeedbackAnswerTypeId,
		CreatedUserId,
		CreatedDateTime 
	 )
	 Values
	 (
		@lNextNumber,
		@rQuestionNumber,
		@rQuestion,
		@rFeedbackTemplateId,
		@rFeedbackAnswerTypeId,
		@rCreatedUserId,
		sCommon.fGetDate()
	 )
	  
	 END
	 ELse 
	 BEGIN
	 SET @lNextNumber = @rFeedbackTemplateQuestionId
	 IF(@rIsDelete = 0)
	 BEGIN
	 UPDATE sCommunication.tFeedbackTemplateQuestion
	 SET
		QuestionNumber=@rQuestionNumber,
		Question=@rQuestion,
		FeedbackAnswerTypeId=@rFeedbackAnswerTypeId,
		UpdatedUserId=@rCreatedUserId,
		UpdatedDateTime=sCommon.fGetDate()
		WHERE Id=@rFeedbackTemplateQuestionId
	 END
	 ELSE 
		DELETE FROM sCommunication.tFeedbackTemplateQuestion  WHERE Id =  @rFeedbackTemplateQuestionId	
	END
	Select 1 As Result
END
GO
PRINT N'Creating [sCommunication].[pFeedbackTypeMasterDelete]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackTypeMasterDelete]

	 @rId int,
	 @rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		--IF NOT EXISTS (SELECT Id FROM sCommunication.tCircular WHERE CircularTypeId = @rId)	
		--BEGIN	
			Delete from sCommunication.tFeedbackAnswerTypeMaster where Id=@rId AND OrgGroupId=@rOrgGroupId
			  
			Delete from sCommunication.tFeedbackAnswerTypeDetail where FeedbackAnswerTypeId=@rId
			Select 1 AS RESULT
		--END
		--ELSE
		--	BEGIN
		--		SELECT -101 AS RESULT
		--	END
			
		
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Creating [sCommunication].[pFeedbackTypeTemplateDelete]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackTypeTemplateDelete]

	 @rId bigint,
	 @rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		--IF NOT EXISTS (SELECT Id FROM sCommunication.tCircular WHERE CircularTypeId = @rId)	
		--BEGIN	
			Delete from sCommunication.tFeedbackTemplate where Id=@rId AND OrgGroupId=@rOrgGroupId
			  
			Delete from sCommunication.tFeedbackTemplateQuestion where FeedbackTemplateId=@rId
			Select 1 AS RESULT
		--END
		--ELSE
		--	BEGIN
		--		SELECT -101 AS RESULT
		--	END
			
		
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Creating [sFee].[pFeeSetupFeeWiseGet]...';


GO
CREATE PROCEDURE [sFee].[pFeeSetupFeeWiseGet]
				
		   
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rFeeId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
		ISNULL(FS.Id,0)AS Id,
		ISNULL(CM.Id,0)AS ClassId,
		ISNULL(CM.Title,'') AS ClassName,
		ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
		ISNULL(FS.BatchId,0)AS BatchId,
		ISNULL(FS.IsOptional,0)AS IsOptional,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'0001-01-01 00:00:00.00')AS StartDate,
		ISNULL(FS.EndDate,'0001-01-01 00:00:00.00')AS EndDate,
		ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
		CASE WHEN (SELECT COUNT(*) FROM sFee.tReceiptDetail WHERE FeeSetupId=FS.Id) <= 0 THEN 'True' ELSE 'False' END AS IsReceiptBookChange,
		ISNULL(FS.IsServiceTax,0)AS IsServiceTax,
		ISNULL(FS.CollectionGroupId,0) AS CollectionGroupId
  FROM 
		sSetup.tClassMaster CM
		INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id AND BC.BatchId = @rBatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		LEFT JOIN sFee.tFeeSetup FS ON CM.Id=FS.ClassId 
		AND (FS.FeeId=@rFeeId OR @rFeeId= 0) 
		AND (FS.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId= 0) 
		AND (FS.BatchId=@rBatchId)
		LEFT JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
WHERE 
		OM.OrgGroupId=@rOrgGroupId
		ORDER BY FS.StartDate,CM.OrderIndex
END
GO
PRINT N'Creating [sFee].[pFeeSetupFeeWiseRemove]...';


GO
CREATE PROCEDURE [sFee].[pFeeSetupFeeWiseRemove]

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

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

			ALTER TABLE sFee.tFeeOptional 
			 WITH CHECK CHECK CONSTRAINT FK_sFee_tFeeOptional_tFeeSetupId 

			ALTER TABLE sFee.tFeeAllocation 
			 WITH CHECK CHECK CONSTRAINT FK_sFee_tFeeAllocation_FeeSetupId

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

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

	
	

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


GO
CREATE PROC [sFee].[pRptExpenseTypeWiseDepositList]

	     
		   @rOrgId int,          
           @rDepositHeadId int=0,         
           @rFromDate date='',
           @rToDate date='',           
           @rStudentName nvarchar(100)='',
		  @rStudentCode nvarchar(100)='',
		  @rClassId int=0,
		  @rDivisionId int=0,
		  @rIsBasedOnSUId bit = 0,
		  @rDepartmentId int=0,
		  @rSUId nvarchar(20)='',
		  @rBatchId int=0,
		  @rBuilder1 nvarchar(max)='',
	      @rBuilder2 nvarchar(max)=''
	    
   
AS
BEGIN
		SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.Studentid   AS AcademicId ,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		    'Add' AS GroupType,
	        '' As ExpenseType,
	         DA.Id As GroupID
		    
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId  
		
			Where 
		  ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))	
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND ((VA.ClassId = @rClassId) OR (@rClassId = 0))
		    AND ((VA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		    AND ((VA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		    AND ((VA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		    AND (VA.OrgId=@rOrgId OR @rOrgId=0)
		    AND (DA.DepositHeadId = @rDepositHeadId)
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			-ISnull (DAJ.Amount,0)  AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     'Adjustment' AS GroupType,
		     ES.Title As ExpenseType,
		     DAJ.Id As GroupID
		    
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  INNER JOIN sFee.tFeeDepositExpenseTypeMaster ES ON ES.Id=DAJ.FeeDepositExpenseTypeId
			Where 
				((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.ClassId = @rClassId) OR (@rClassId = 0))
		    AND ((VA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		    AND ((VA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		    AND ((VA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		    AND (VA.OrgId=@rOrgId OR @rOrgId=0)
		    AND (DAJ.DepositHeadId = @rDepositHeadId)
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			-ISnull (DR.RefundAmount,0)  AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') AS  SUId, 
		    'Refund' AS GroupType,
		    '' As ExpenseType,
		    DR.Id As GroupID
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			Where 
			((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.ClassId = @rClassId) OR (@rClassId = 0))
		    AND ((VA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		    AND ((VA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		    AND ((VA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		    AND (VA.OrgId=@rOrgId OR @rOrgId=0)
		  
		    AND (DR.DepositHeadId = @rDepositHeadId)
END
GO
PRINT N'Creating [sHostel].[PHostelDepositAddAllDelete]...';


GO

CREATE PROCEDURE [sHostel].[PHostelDepositAddAllDelete]
	 
	      @rHostelId int,
          @rOrgGroupBatchId int,
          @rHostelDepositHeadId int,
          @rDepositId bigint,
          @rStudentId bigint
     
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	BEGIN TRY
			
			
	IF EXISTS (SELECT 1 FROM  sHostel.tHostelDepositAdjustment WHERE StudentId=@rStudentId AND HostelDepositHeadId=@rHostelDepositHeadId AND OrgGroupBatchId=@rOrgGroupBatchId AND HostelId=@rHostelId)
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END
	ELSE 
	IF EXISTS (SELECT 1 FROM  sHostel.tHostelDepositRefund WHERE StudentId=@rStudentId AND HostelDepositHeadId=@rHostelDepositHeadId  AND OrgGroupBatchId=@rOrgGroupBatchId AND HostelId=@rHostelId)
	BEGIN
		SELECT -102 AS RESULT
		RETURN
	END
	ELSE 
	BEGIN TRANSACTION
	BEGIN
		DELETE  sHostel.tHostelDepositAdd
		FROM sHostel.tHostelDepositAdd DA
		WHERE DA.Id=@rDepositId AND  DA.OrgGroupBatchId=@rOrgGroupBatchId
		AND DA.HostelId=@rHostelId  AND HostelDepositHeadId=@rHostelDepositHeadId 
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END
GO
PRINT N'Creating [sHostel].[PHostelDepositListGet]...';


GO

CREATE PROCEDURE [sHostel].[PHostelDepositListGet]
	 
	      @rHostelId int,
	      @rRoomId int,
          @rOrgGroupBatchId int,
          @rStudentCode   nvarchar(max)='',
          @rSUId nvarchar(max)='',
          @rHostelDepositHeadId int
     
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT
	    DHM.Title AS DepositHeadName,
		DA.Id AS DepositId,
	    DA.Studentid AS Studentid,
		DA.Amount,
		DA.DepositDate,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
       ISNULL(VSA.SUID,'') AS SUID,
       RM.Title AS Room,
       	DA.HostelDepositHeadId
  FROM 		
		sHostel.tAssignRoom AR 
		INNER JOIN sStudent.vStudentAcademic vSA ON vSA.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sHostel.tHostelDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId 
		INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id
	
		WHERE	
			 (DA.HostelId=@rHostelId)
			AND DA.OrgGroupBatchId=@rOrgGroupBatchId
			AND vSA.OrgGroupBatchId=@rOrgGroupBatchId
			AND ((DA.HostelDepositHeadId = @rHostelDepositHeadId) OR (ISNULL(@rHostelDepositHeadId,0) = 0))
			AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
			AND (ISNULL(vSA.SUID,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
	        AND (ISNULL(vSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 
	    
			Order By VSA.SUID,VSA.Code
END
GO
PRINT N'Creating [sHrm].[pEmployeeLateStatusAdd]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeLateStatusAdd]
           
        @rEmployeeId bigint,
        @rLateDate date,  
        @rLateStatus nvarchar(10),
        @rIsApproved bit=0,
        @rCreatedUserId bigint
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	BEGIN TRANSACTION
		  INSERT INTO sBiometric.tEmployeeLateStatus
          (
		   EmployeeId,
		   LateDate,
		   LateStatus,
		   IsApproved,
		   CreatedUserId,
		   CreatedDateTime,
		   UpdatedUserId,
		   UpdatedDateTime
          )
     VALUES
           (
            @rEmployeeId,
            @rLateDate,
            @rLateStatus,
            @rIsApproved,
            @rCreatedUserId,
            sCommon.fGetDate(),
            @rCreatedUserId,
            sCommon.fGetDate()
           )
	
	SELECT 1 AS Result	   
	   
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Creating [sLibrary].[pAssignBooksBulkReturnGet]...';


GO

CREATE PROCEDURE [sLibrary].[pAssignBooksBulkReturnGet]
	 
	 @rLibraryId int,
	 @rClassId int,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rDivisionId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

	SELECT 
	Distinct VA.StudentId,
	VA.Name,
	VA.Code,
	VA.RollNo,
	VA.StudentId
	 
  FROM 
  sStudent.vStudentLastAcademic  VA
  INNER JOIN sLibrary.tBookLog BL ON VA.StudentId=BL.ReaderSourceId AND  BL.IsCurrentStatus=1 AND  BL.ReaderSourceTypeId=2003
  	AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
 
  WHERE   
 VA.ClassId=@rClassId
 AND VA.BatchId=@rBatchId
 AND VA.OrgId=@rOrgId
 AND ((VA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
 order by VA.RollNo
    
END
GO
PRINT N'Creating [sProcurement].[pStockBatchAddUpdate]...';


GO
 
CREATE PROCEDURE [sProcurement].[pStockBatchAddUpdate]
    
    --@rId bigint=0,
	@rStoreLocationId int=0,
	--@rStockItemId int=0,
	--@rNumber nvarchar(20)='',
	--@rStockItemTypeId [int],
	--@rExpiryDate date='',	 
	 @rAvailableQuantity decimal(12,2)=0,	 
	--@rCreatedUserId bigint=0,
	@rOrgGroupId smallint=0,
	--@rPrice decimal(12,2)=0,
	@rStockInwardDetailId int=0,
	@rbatchNo int=0
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

  
BEGIN
	--Declare @lAvailableQty decimal(12,2)
	--Select @lAvailableQty = AvailableQuantity from sProcurement.tStockBatch where Id=@rbatchNo  AND StoreLocationId=@rStoreLocationId AND OrgId=@rOrgId
 --Select @lAvailableQty
	--if(@rId=0)
	--BEGIN

	 DECLARE @lNextNumber INT 
	EXECUTE sCommon.pTableRowIdGet  @rOrgGroupId, 'sProcurement.tStockInwardBatch', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sProcurement.tStockInwardBatch
	(
		Id,StockInwardDetailId,Quantity,StockBatchId,OrgGroupId
	)
	Values
	(
		@lNextNumber,@rStockInwardDetailId,@rAvailableQuantity,@rbatchNo,@rOrgGroupId
	)
	Select 1 as result
	--EXECUTE sCommon.pTableRowIdGet  @rOrgId, 'sProcurement.tStockBatch', 0, 1, 1,@outNextNumber = @lNextNumber output

	--INSERT INTO sProcurement.tStockBatch
	--	(
	--		Id,
	--		 StoreLocationId,
	--		 StockItemId,
	--		 Number,
	--		 ExpiryDate,
	--		 AvailableQuantity,
	--		 CreatedUserId,
	--		 CreatedDateTime,
	--		 OrgId,
	--		 Price
			 
	--	)
	--VALUES
	--	(
	--		@lNextNumber,
	--		 @rStoreLocationId,
	--		 @rStockItemId,
	--		 @rNumber,
	--		 @rExpiryDate,
	--		 @rAvailableQuantity,
	--		 @rCreatedUserId,
	--		 sCommon.fGetDate(),
	--		 @rOrgId,
	--		 @rPrice
	--	)
	--END
	--else
	--BEGIN
	--	Update sProcurement.tStockBatch Set AvailableQuantity =@lAvailableQty + @rAvailableQuantity 
	--	WHere Id=@rId
	--END
	 
 END
GO
PRINT N'Creating [sProcurement].[pStockInwardDetailGet]...';


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

BEGIN
	  
 
SELECT		SIDe.Id,
			SIDe.StockInwardId,
			SIDe.StockItemId,
			SIDe.RequestedQuantity,
			--SIDe.InwardQuantity,
			 SIDe.InwardValue ,
			SIDe.Remark,
			SIM.Code				AS StockItemCode,
			SIM.Title				AS StockItemName,
			 SUMa.Code				AS UOM,
			SIM.IsBatchWiseTracking ,
			ISNULL(B.Id,0) As StockInwardBatchId,
			ISNULL(B.StockBatchId,0) AS StockBatchId,
			 
			B.Quantity AS InwardQuantity,
			--ISNULL(B.Value,0) AS InwardValue,
			SB.Number AS 'Batch No',
			ISNULL(SB.ExpiryDate,'') AS ExpiryDate,
			ISNULL(SB.AvailableQuantity,0) As AvailableQuantity ,
		 
			ISNULL(VM.Code,'') AS VendorCode,
			ISNULL(VM.Id,0) AS VendorId
			 
			
 
FROM		sProcurement.tStockInwardDetail SIDe
INNER JOIN	sProcurement.tStockInward SI
			ON SI.Id = SIDe.StockInwardId
			LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id= SI.VendorId
INNER JOIN	sIp.tStockItemMaster SIM
			ON SIM.Id = SIDe.StockItemId 
 INNER JOIN  sFinanceCommon.tStockUomMaster SUMa
 		ON SUMa.Id = SIM.IssueStockUomId
			LEFT JOIN sProcurement.tStockInwardBatch B ON B.StockInwardDetailId= SIDe.Id
			LEFT JOIN	sProcurement.tStockBatch SB
			ON SB.Id = B.StockBatchId 
		 
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId

 
END
GO
PRINT N'Creating [sProcurement].[pStockReset]...';


GO
 
CREATE PROCEDURE [sProcurement].[pStockReset]
	@rOrgGroupId smallint, 
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
SELECT		SI.Id,
			SI.Number,
			isnull(SI.ResetByName,'') as ResetByName,
			SI.CreatedDateTime			AS ResetDate,
			SLM.Code					AS ToStoreLocationCode
FROM		sProcurement.tStockReset SI
INNER JOIN	sIp.tStoreLocationMaster SLM
			ON SLM.Id = SI.ToStoreLocationId 		
WHERE		 
 			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = '*'))
		AND        SI.OrgGroupId = @rOrgGroupId	
		AND ((SI.CreatedDateTime>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SI.CreatedDateTime<=DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
		AND SI.ToStoreLocationId =@rStoreLocationId
Order by  SI.Number desc,
 SI.CreatedDateTime desc
END
GO
PRINT N'Creating [sProcurement].[pStockResetAdd_New]...';


GO
 

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

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

	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1005,
	@rStoreLocationId = @rToStoreLocationId, @rNextNumber  = @rNumber OUTPUT
	
	SET @rNumber = ISNULL(@rNumber, '-300')
	IF @rNumber = '-300'
	BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id 
		RETURN
	END


	DECLARE @tStockResetDetailBatch TABLE
	(
		Id Int IDENTITY(1, 1),	 
		StockItemId bigint,
		StockItemName nvarchar(max),
		ItemBatch Nvarchar(max) NULL,
		ItemExpiryDate Date NULL,	
		ResetQuantity Decimal(12,2),
		RequestedQuantity Decimal(12,2),
		ResetValue Decimal(12,2)
	)	
    INSERT INTO @tStockResetDetailBatch
    SELECT
            T.c.value('@StockItemId','bigint') AS StockItemId,
            T.c.value('@StockItemName','nvarchar(max)') AS StockItemname,
            T.c.value('@ItemBatch','Nvarchar(max)') AS ItemBatch,
            T.c.value('@ItemExpiryDate','Date')   AS ItemExpiryDate,
            T.c.value('@ResetQuantity','Decimal(12,2)') AS ResetQuantity,
            T.c.value('@RequestedQuantity','Decimal(12,2)') AS RequestedQuantity,
            T.c.value('@ResetValue','Decimal(12,2)') AS ResetValue 
    FROM 
            @loXML.nodes('/Table/StockReset')T(c)


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

	INSERT INTO sProcurement.tStockReset
	(
		Id,Number,ResetByName,ToStoreLocationId,Remark,CreatedUserId,CreatedDateTime,OrgGroupId
	)
	VALUES
	(
		@lNextNumberStockReset,@rNumber,
		@rResetByName,@rToStoreLocationId,@rRemark,@rCreatedUserId,sCommon.fGetDate(),
		@rOrgGroupId
	)
            
	declare @lCount int,@lIsBatchWise bit,@lbatchId int,@lNextNumberStockBatch int,@lExpiryDate date
	Declare @lItemId int,@lBatch nvarchar(300),@lResetQty decimal(12,2),@lResetValue decimal(12,2),@lIdCount int
	DECLARE @lStockItemname nvarchar(max)
	select @lCount=COUNT(*) from @tStockResetDetailBatch 
		 
	while @lcount > 0
	BEGIN
					 
		Select @lItemId =StockItemId,@lBatch = ItemBatch,@lResetQty=ResetQuantity,@lResetValue=ResetValue,@lIdCount=Id,@lExpiryDate =ItemExpiryDate 
		,@lStockItemname=StockItemname
		from  @tStockResetDetailBatch WHERE Id = @lcount
		Select @lIsBatchWise=IsBatchWiseTracking from sIp.tStockItemMaster    Where Id = @lItemId   
		 
		SET @lbatchId = 0
		 
			if (@lIsBatchWise=1)
			BEGIN		
							
				Select @lbatchId= Id from sProcurement.tStockBatch    
				Where  Number =@lBatch   AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId --AND @lIdCount=@lcount
				 
			END
			else 
			BEGIN
				
				Select @lbatchId= Id from sProcurement.tStockBatch    
				Where iSNULl( Number,'') =''  AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId--AND  @lIdCount=@lcount
			 
			END

			if(ISNULL(@lbatchId,0)=0)
			BEGIN
				  
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockBatch output
				 INSERT INTO sProcurement.tStockBatch (Id,StoreLocationId,StockItemId,Number,ExpiryDate,AvailableQuantity,CreatedUserId,CreatedDateTime,OrgGroupId,ItemRate)
				Select @lNextNumberStockBatch,@rToStoreLocationId,@lItemId,@lBatch,@lExpiryDate ,@lResetQty,@rCreatedUserId,getdate(),@rOrgGroupId,@lResetValue
				--from @tStockResetDetailBatch where Id=@lcount
				
				 SET @lbatchId = @lNextNumberStockBatch
				 
				 
			END 
			 	 
			 if(@lbatchId>0)
			BEGIN
					 
				 EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockResetBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockResetBatch output
				
						INsert into sProcurement.tStockResetBatch(Id,StockResetId,Quantity,StockBatchId,OrgGroupId,UnitCost)
						Select @lNextNumberStockResetBatch,@lNextNumberStockReset,ResetQuantity,@lbatchId,@rOrgGroupId,ResetValue
						from @tStockResetDetailBatch where Id=@lcount
			 
						Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=2028,@rSourceId=@lNextNumberStockResetBatch,
								@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lResetQty ,@rValue=@lResetValue,@rIsReceipt=1,
								@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rToStoreLocationId
								,@rLocationId=@rLocationId,@rItemBatchId = @lbatchId,@rItemName = @lStockItemname,@rOrgId=@rOrgId		
								
						 
			 END
			set @lcount =@lcount-1
		END
		
		SELECT 1 AS RESULT , @rNumber as Number,@lNextNumberStockReset as Id
		 COMMIT TRANSACTION
        END TRY
         
        BEGIN CATCH
        IF @@TRANCOUNT > 0  
		ROLLBACK TRANSACTION
		 
		SELECT -1 AS RESULT , @rNumber as Number,@lNextNumberStockReset as Id
	    END CATCH	
END
GO
PRINT N'Creating [sProcurement].[pStockResetDetailGet]...';


GO
 
CREATE PROCEDURE [sProcurement].[pStockResetDetailGet]
	@rOrgGRoupId smallint,
	@rId [bigint] = 0,
	@rNumber [nvarchar](20) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
 
SELECT		SIDe.Id,
			SIDe.StockResetId,
			SB.StockItemId,			
			SIM.Code				AS StockItemCode,
			SIM.Title				AS StockItemName,
			SUMa.Code				AS UOM,
			SIM.IsBatchWiseTracking ,
			ISNULL(SIDe.Id,0) As StockResetBatchId,
			ISNULL(SIDe.StockBatchId,0) AS StockBatchId,
			SIDe.Quantity AS ResetQuantity,
			ISNULL(SIDe.UnitCost,0) AS ResetValue,
			SB.Number AS 'Batch No',
			ISNULL(SB.ExpiryDate,'') AS ExpiryDate,
			ISNULL(SB.AvailableQuantity,0) As AvailableQuantity 

FROM		sProcurement.tStockResetBatch SIDe
INNER JOIN	sProcurement.tStockReset SI
			ON SI.Id = SIDe.StockResetId
INNER JOIN	sProcurement.tStockBatch SB
			ON SB.Id = SIDe.StockBatchId 
INNER JOIN	sIp.tStockItemMaster SIM
			ON SIM.Id = SB.StockItemId 	
INNER JOIN  sFinanceCommon.tStockUomMaster SUMa
 			ON SUMa.Id = SIM.IssueStockUomId			
		 
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGRoupId

 
END
GO
PRINT N'Creating [sProcurement].[pStockResetGet]...';


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

BEGIN
	  
SELECT		SI.Id,
			SI.Number,
			SI.ResetByName,
			SI.ToStoreLocationId,			
			SI.Remark,
			SI.CreatedUserId			AS UserId,
			SI.CreatedDateTime			AS ResetDate,
			SLM.Code					AS ToStoreLocationCode
			
FROM		sProcurement.tStockReset SI
INNER JOIN	sIp.tStoreLocationMaster SLM
			ON SLM.Id = SI.ToStoreLocationId 		
			
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId



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

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


GO
 
 
 
CREATE PROCEDURE [sSetup].[pPortalExemptionTypeDetailAdd]
	
	@rStrXml nvarchar(MAX) 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
	 DELETE  FROM sFee.tExemptionTypeDetail 
	 
	 INSERT INTO sFee.tExemptionTypeDetail
		(
			ExemptionTypeId,
			FeeId,
			ExemptionPercentage
		 
			 
			)
		SELECT		
			 ExemptionTypeId,
			 FeeId,
			 ExemptionPercentage
			  
		FROM OPENXML (@loDoc, '/Table/FeeMaster', 1)
		WITH ( 
				ExemptionTypeId int,
				FeeId int,
				 ExemptionPercentage decimal(8,2) 
			  )  
		--EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalFeeAllocationAdd]...';


GO
 
 
 
CREATE PROCEDURE [sSetup].[pPortalFeeAllocationAdd]
	
	@rStrXml nvarchar(MAX) ,
	@rBatchId Int,
	@rDivisionId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 Delete f from sFee.tFeeAllocation F INNER JOIN sFee.tFeeSetup FS ON FS.Id=F.FeeSetupId
	 Where FS.BatchId=@rBatchId
	 INSERT INTO sFee.tFeeAllocation
		(
			SourceTypeId,
			SourceId,
			FeeSetupId ,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			ReferenceTypeId,
			ReferenceSourceId,
			CreatedUserId,
			CreatedDateTime ,
			UpdatedUserId,
			UpdatedDateTime
			)
		SELECT		
			 A.SourceTypeId,
			A.SourceId,
			A.FeeSetupId,
			A.VariableAmount,
			A.DiscountAmount,
			A.AdditionalAmount,
			A.NotApplicableAmount,
			A.Remark,
			A.ReferenceTypeId,
			A.ReferenceSourceId,
			A.CreatedUserId,
			A.CreatedDateTime ,
			A.UpdatedUserId,
			A.UpdatedDateTime
		
		FROM OPENXML (@loDoc, '/Table/FeeAllocation', 1)
		WITH ( 
				
			    SourceTypeId smallint,
			    SourceId  bigint,
			    FeeSetupId int,
			    VariableAmount decimal(12, 2),
			    DiscountAmount decimal(12, 2),
			    AdditionalAmount  decimal(12, 2),
			    NotApplicableAmount decimal(12, 2),
			    Remark nvarchar(200),
			    ReferenceTypeId smallint,
			    ReferenceSourceId bigint,
			    CreatedUserId bigint,
			    CreatedDateTime datetime,
			    UpdatedUserId bigint,
			    UpdatedDateTime datetime
			  )A
		INNER JOIN sStudent.tAcademic FS ON FS.Id=A.SourceId
		WHere FS.DivisionId=@rDivisionId
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalFeeCollectionGroupAdd]...';


GO
 
 
CREATE PROCEDURE [sSetup].[pPortalFeeCollectionGroupAdd]
	
	@rStrXml nvarchar(MAX),
    @rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE  FROM sFee.tCollectionGroupMaster WHERE OrgGroupBatchId=@rOrgGroupBatchId
	 
	 INSERT INTO sFee.tCollectionGroupMaster
		(
			OrgGroupBatchId,
			Id,
			Code,
			Title,
			StartDate,
			EndDate,
			Remark,
			IsObsolete,
			OrderIndex,
			ReceiptBookId,
			FooterRemark1,
			FooterRemark2,
			FeePeriod,
			IsDisplayCashDetailInFolio,
			ReportId,
			IsOnPrePrinted
			)
		SELECT		
			OrgGroupBatchId,
			Id,
			Code,
			Title,
			StartDate,
			EndDate,
			Remark,
			IsObsolete,
			OrderIndex,
			ReceiptBookId,
			FooterRemark1,
			FooterRemark2,
			FeePeriod,
			IsDisplayCashDetailInFolio,
			ReportId,
			IsOnPrePrinted
						
		FROM OPENXML (@loDoc, '/Table/FeeCollectionMaster', 1)
		WITH ( 
				OrgGroupBatchId int,
				Id int,
			    Code nvarchar(20),
			    Title nvarchar(100),
			    StartDate date,
			    EndDate date,
			    Remark nvarchar(500),
			    IsObsolete bit,
			    OrderIndex smallint,
			    ReceiptBookId int,
			    FooterRemark1 nvarchar(200),
			    FooterRemark2 nvarchar(200),
			    FeePeriod nvarchar(100),
			    IsDisplayCashDetailInFolio bit,
			    ReportId int,
			    IsOnPrePrinted bit
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalFeeDiscountAdd]...';


GO
 
 
 
 
CREATE PROCEDURE [sSetup].[pPortalFeeDiscountAdd]
	
	@rStrXml nvarchar(MAX) 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 
	 INSERT INTO sFee.tFeeDiscount
		(
			SourceTypeId,
			SourceId,
			FeeSetupId ,
			RequestedDiscountAmount,
			RequestedRemark,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			ApprovedByUserId,
			ApprovedDiscountAmount,
			ApprovedRemark 
			)
		SELECT		
			 SourceTypeId,
			SourceId,
			FeeSetupId,
			RequestedDiscountAmount,
			RequestedRemark,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			ApprovedByUserId,
			ApprovedDiscountAmount,
			ApprovedRemark 
		
		FROM OPENXML (@loDoc, '/Table/FeeDiscount', 1)
		WITH ( 
				
			    SourceTypeId smallint,
			    SourceId  bigint,
			    FeeSetupId int,
			    RequestedDiscountAmount decimal(12, 2),
			    RequestedRemark nvarchar(200),
			    CreatedUserId  bigint,
			    CreatedDateTime datetime,
			    UpdatedUserId bigint,
			    UpdatedDateTime datetime,
			    ApprovedByUserId bigint,
			    ApprovedDiscountAmount decimal(12, 2),
			    ApprovedRemark nvarchar(200) 
			  )  
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalFeeExamptionTypeMasterAdd]...';


GO
 
 
 
CREATE PROCEDURE [sSetup].[pPortalFeeExamptionTypeMasterAdd]
	
	@rStrXml nvarchar(MAX),
    @rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE  FROM sFee.tExemptionTypeMaster WHERE OrgGroupId=@rOrgGroupId
	 
	 INSERT INTO sFee.tExemptionTypeMaster
		(
			Id,
			Code,
			Number,
			Title,
			OrgGroupId,
			IsObsolete,
			OrderIndex,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			CalculationTypeId 
			)
		SELECT		
			 
			Id,
			Code,
			Number,
			Title,
			OrgGroupId,
			IsObsolete,
			OrderIndex,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			CalculationTypeId 
						
		FROM OPENXML (@loDoc, '/Table/FeeExemptionTypeMaster', 1)
		WITH ( 
				Id int,
			    Code nvarchar(20),
			    Number nvarchar(100),
			    Title nvarchar(100),
			    OrgGroupId  smallint,
			    IsObsolete bit,
			    OrderIndex smallint,
			    CreatedUserId bigint,
			    CreatedDateTime datetime,
			    UpdatedUserId bigint,
			    UpdatedDateTime datetime,
			    CalculationTypeId tinyint 
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalFeeMasterAdd]...';


GO
 
 
CREATE PROCEDURE [sSetup].[pPortalFeeMasterAdd]
	
	@rStrXml nvarchar(MAX) ,
    @rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
	 DELETE  FROM sFee.tFeeMaster WHERE OrgGroupId=@rOrgGroupId
	 
	 INSERT INTO sFee.tFeeMaster
		(
			OrgGroupId,
			Id,
			Code ,
			Number,
			Title,
			FeeHeadId,
			OrderIndex,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			UpdatedUserId,
			UpdatedDateTime
		 
			 
			)
		SELECT		
			 OrgGroupId,
			 Id,
			 Code ,
			 Number,
			 Title,
			 FeeHeadId,
			 OrderIndex,
			 CreatedUserId,
			 CreatedDateTime,
			 IsObsolete,
			 UpdatedUserId,
			 UpdatedDateTime
			  
		FROM OPENXML (@loDoc, '/Table/FeeMaster', 1)
		WITH ( 
				OrgGroupId smallint,
				Id int,
				Code nvarchar(20),
				 Number int,
				 Title nvarchar(100),
				 FeeHeadId int,
				 OrderIndex int,
				 CreatedUserId bigint,
				 CreatedDateTime datetime,
				 IsObsolete bit,
				 UpdatedUserId bigint,
				 UpdatedDateTime datetime
				 
			  )  
		--EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalFeeOptionalAdd]...';


GO
 
CREATE PROCEDURE [sSetup].[pPortalFeeOptionalAdd]
	
	@rStrXml nvarchar(MAX) ,
    @rDivisionId int,
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT,@lCount int 
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	 BEGIN TRY
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 Delete from sFee.tFeeOptional Where BatchId=@rBatchId
	  INSERT INTO sFee.tFeeOptional
		(
			FeeSetupId,
			SourceTypeId,
			SourceId ,
			BatchId 
			)
		SELECT		
			A.FeeSetupId,
			A.SourceTypeId,
			A.SourceId ,
			A.BatchId 
		
		FROM OPENXML (@loDoc, '/Table/Optional', 1)
		WITH ( 
				
			   FeeSetupId  int,
			SourceTypeId  int,
			SourceId bigint,
			BatchId int 
			  ) A
	INNER JOIN sStudent.tAcademic AB ON AB.Id=A.SourceId
	WHere AB.DivisionId=@rDivisionId
		
	 
        SELECT 1 AS Result
	  END	
	
	
		COMMIT TRANSACTION
		END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sSetup].[pPortalFeeSetupAdd]...';


GO
 
 
CREATE PROCEDURE [sSetup].[pPortalFeeSetupAdd]
	
	@rStrXml nvarchar(MAX) ,
	@rBatchId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	 
	  BEGIN TRY
	 BEGIN TRANSACTION 
	 BEGIN
 
	 --Delete RT from 	sFee.tFeeAllocation RT INNER JOIN #temptable T On t.id=RT.feeSetupId
	 --delete RT from sFee.tReceiptDetail RT INNER JOIN #temptable T On T.id=RT.FeeSetupId
	 --delete Fo from sFee.tFeeOptional fo  Inner join #temptable T On T.Id=fo.FeeSetUpid
	 EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
	 DELETE  FROM sFee.tFeeSetup WHERE BatchId=@rBatchId 
	 INSERT INTO sFee.tFeeSetup
		(
			Id,
			ClassId  ,
			AdmissionCategoryId,
			BatchId,
			FeeId,
			IsVariable,
			IsOptional,
			Amount,
			StartDate,
			EndDate,
			ReceiptBookId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsServiceTax,
			CollectionGroupId
			)
		SELECT		
			Id,
			 ClassId ,
			 AdmissionCategoryId,
			 BatchId,
			 FeeId,
			 IsVariable,
			 IsOptional,
			 Amount,
			 StartDate,
			 EndDate,
			 ReceiptBookId,
			 CreatedUserId,
			 CreatedDateTime,
			 UpdatedUserId,
			 UpdatedDateTime,
			 IsServiceTax,
			 CollectionGroupId
			  
		FROM OPENXML (@loDoc, '/Table/FeeSetup', 1)
		WITH ( 
				Id int ,
				ClassId int,
				AdmissionCategoryId int,
				BatchId int,
				FeeId int,
				IsVariable bit,
				IsOptional bit,
				Amount decimal(12,2),
				StartDate date,
				EndDate date,
				ReceiptBookId int,
				CreatedUserId bigint,
				CreatedDateTime date,
				UpdatedUserId bigint,
				UpdatedDateTime date,
				IsServiceTax bit,
				CollectionGroupId int
			  )  
		--EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
        SELECT 1 AS Result
	   END	
	
	
		COMMIT TRANSACTION
		END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalHeadMasterAdd]...';


GO
 
 
CREATE PROCEDURE [sSetup].[pPortalHeadMasterAdd]
	
	@rStrXml nvarchar(MAX),
    @rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
	 DELETE  FROM sFee.tFeeHeadMaster WHERE OrgGroupId=@rOrgGroupId
	 
	 INSERT INTO sFee.tFeeHeadMaster
		(
			OrgGroupId,
			Id,
			Number,
			Code,
			Title,
			CreatedUserId,
			CreatedDateTime,
			OrderIndex,
			IsObsolete,
			UpdatedUserId,
			UpdatedDateTime
			)
		SELECT		
			 OrgGroupId,
			 Id,
			 Number,
			 Code,
			 Title,
			 CreatedUserId,
			 CreatedDateTime,
			 OrderIndex,
			 IsObsolete,
			 UpdatedUserId,
			 UpdatedDateTime
		
		FROM OPENXML (@loDoc, '/Table/HeadMaster', 1)
		WITH ( 
				OrgGroupId smallint,
				Id int,
				Number int,
				Code nvarchar(20),
				Title nvarchar(100),
				CreatedUserId bigint,
				CreatedDateTime datetime,
				OrderIndex  smallint,
				IsObsolete bit,
				UpdatedUserId bigint,
				UpdatedDateTime datetime
			  )  
		--EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

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


GO
 
 
CREATE PROCEDURE [sSetup].[pPortalHeadOrgwiseAdd]
	
	@rStrXml nvarchar(MAX),
    @rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE  FROM sFee.tFeeHeadOrgwise WHERE OrgId=@rOrgId
	 
	 INSERT INTO sFee.tFeeHeadOrgwise
		(
			OrgId,
			 FeeId
			)
		SELECT		
			 OrgId,
			 FeeId 
		
		FROM OPENXML (@loDoc, '/Table/HeadOrgwise', 1)
		WITH ( 
				OrgId smallint,
				FeeId int 
			  )  
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalMainGroupMasterAdd]...';


GO
 
 
CREATE PROCEDURE [sSetup].[pPortalMainGroupMasterAdd]
	
	@rStrXml nvarchar(MAX) 
     
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE  FROM sFee.tFeeMainGroupMaster 
	 
	 INSERT INTO sFee.tFeeMainGroupMaster 
		(
			Id,
			Number,
			Code,
			Title,
			IsObsolete 
			 
			)
		SELECT		
			 Id,
			 Number,
			 Code,
			 Title,
			 IsObsolete 
			  
		FROM OPENXML (@loDoc, '/Table/MainGroupMaster', 1)
		WITH ( 
				Id int,
				Number int,
				Code nvarchar(20),
				Title nvarchar(100),
				IsObsolete bit 
				 
			  )  
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalMainGroupOptionalFeeAdd]...';


GO
 
 
 
CREATE PROCEDURE [sSetup].[pPortalMainGroupOptionalFeeAdd]
	
	@rStrXml nvarchar(MAX) ,
    @rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE  FROM sFee.tFeeMainGroupOptionalFee WHERE OrgId=@rOrgId
	 
	 INSERT INTO sFee.tFeeMainGroupOptionalFee
		(
			OrgId,
			FeeMainGroupId,
			FeeId 
		 
			 
			)
		SELECT		
			 OrgId,
			 FeeMainGroupId,
			 FeeId 
			 
			  
		FROM OPENXML (@loDoc, '/Table/MainGroupOptionalFee', 1)
		WITH ( 
				OrgId int,
				FeeMainGroupId int,
				FeeId int 
				 
			  )  
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalMainGroupOrgGroupwiseAdd]...';


GO
 
 
CREATE PROCEDURE [sSetup].[pPortalMainGroupOrgGroupwiseAdd]
	
	@rStrXml nvarchar(MAX) ,
    @rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE  FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId=@rOrgGroupId
	 
	 INSERT INTO sFee.tFeeMainGroupOrgGroupwise
		(
			OrgGroupId,
			FeeMainGroupId,
			FeeHeadId 
		 
			 
			)
		SELECT		
			 OrgGroupId,
			 FeeMainGroupId,
			 FeeHeadId 
			 
			  
		FROM OPENXML (@loDoc, '/Table/MainGroupOrgGroupwise', 1)
		WITH ( 
				OrgGroupId int,
				FeeMainGroupId int,
				FeeHeadId int 
				 
			  )  
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalReceiptAdd]...';


GO
 
 
 
CREATE PROCEDURE [sSetup].[pPortalReceiptAdd]
	
	@rStrXml nvarchar(MAX) ,
	@rDivisionID int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT,@lCount int 
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	 BEGIN TRY
	 BEGIN TRANSACTION 
	 BEGIN 
		 
			Update  sFee.tReceipt
			Set SourceTypeId=A.SourceTypeId,
			SourceId=A.SourceId,
			ReceiptNumber=A.ReceiptNumber,
			ReceiptDate=A.ReceiptDate,
			ReceiptAmount=A.ReceiptAmount,
			PayTypeId=A.PayTypeId,
			ChequeNo=A.ChequeNo,
			BankName=A.BankName,
			ReceiptBookId=A.ReceiptBookId,
			Remark=A.Remark,
			IsObsolete=A.IsObsolete ,
			BatchId=A.BatchId,
			OrgGroupBatchId=A.OrgGroupBatchId,
			CreatedUserId=A.CreatedUserId,
			CreatedDateTime=A.CreatedDateTime,
			TotalReceiptAmount=A.TotalReceiptAmount,
			DiscountAmount=A.DiscountAmount,
			IsChequeCleared=A.IsChequeCleared,
			ChequeClearDate=A.ChequeClearDate,
			ChequeDate=A.ChequeDate,
			FeeInvoiceId=A.FeeInvoiceId,
			CollectionGroupId=A.CollectionGroupId
			From  (
				SELECT		
					Id,
					SourceTypeId,
					SourceId ,
					ReceiptNumber,
					ReceiptDate,
					ReceiptAmount,
					PayTypeId,
					ChequeNo,
					BankName,
					ReceiptBookId,
					Remark,
					IsObsolete ,
					BatchId,
					OrgGroupBatchId,
					CreatedUserId,
					CreatedDateTime,
					TotalReceiptAmount,
					DiscountAmount,
					IsChequeCleared,
					ChequeClearDate,
					ChequeDate,
					FeeInvoiceId,
					CollectionGroupId
				 
				FROM OPENXML (@loDoc, '/Table/Receipt', 1)
				WITH ( 
						
					Id bigint,
					SourceTypeId smallint,
					SourceId bigint,
					ReceiptNumber int,
					ReceiptDate date,
					ReceiptAmount decimal(12, 2),
					PayTypeId tinyint,
					ChequeNo nvarchar(20),
					BankName nvarchar(200),
					ReceiptBookId int,
					Remark nvarchar(200),
					IsObsolete  bit,
					BatchId int,
					OrgGroupBatchId int,
					CreatedUserId bigint,
					CreatedDateTime datetime,
					TotalReceiptAmount decimal(12, 2),
					DiscountAmount decimal(12, 2),
					IsChequeCleared bit,
					ChequeClearDate date,
					ChequeDate date, 
					FeeInvoiceId bigint,
					CollectionGroupId int
					)  
			)A
			INNER JOIN sStudent.tAcademic FS On FS.Id=A.SourceId
			Where sFee.tReceipt.Id=A.Id AND FS.DivisionId=@rDivisionID
			
			INsert INTO sFee.tReceipt
			(
			Id,
					SourceTypeId,
					SourceId ,
					ReceiptNumber,
					ReceiptDate,
					ReceiptAmount,
					PayTypeId,
					ChequeNo,
					BankName,
					ReceiptBookId,
					Remark,
					IsObsolete ,
					BatchId,
					OrgGroupBatchId,
					CreatedUserId,
					CreatedDateTime,
					TotalReceiptAmount,
					DiscountAmount,
					IsChequeCleared,
					ChequeClearDate,
					ChequeDate,
					FeeInvoiceId,
					CollectionGroupId
			)
			SELECT		
					A.Id,
					A.SourceTypeId,
					A.SourceId ,
					A.ReceiptNumber,
					A.ReceiptDate,
					A.ReceiptAmount,
					A.PayTypeId,
					A.ChequeNo,
					A.BankName,
					A.ReceiptBookId,
					A.Remark,
					A.IsObsolete ,
					A.BatchId,
					A.OrgGroupBatchId,
					A.CreatedUserId,
					A.CreatedDateTime,
					A.TotalReceiptAmount,
					A.DiscountAmount,
					A.IsChequeCleared,
					A.ChequeClearDate,
					A.ChequeDate,
					A.FeeInvoiceId,
					A.CollectionGroupId
				 
				FROM OPENXML (@loDoc, '/Table/Receipt', 1)
				WITH ( 
						
					   Id bigint,
					SourceTypeId smallint,
					SourceId bigint,
					ReceiptNumber int,
					ReceiptDate date,
					ReceiptAmount decimal(12, 2),
					PayTypeId tinyint,
					ChequeNo nvarchar(20),
					BankName nvarchar(200),
					ReceiptBookId int,
					Remark nvarchar(200),
					IsObsolete  bit,
					BatchId int,
					OrgGroupBatchId int,
					CreatedUserId bigint,
					CreatedDateTime datetime,
					TotalReceiptAmount decimal(12, 2),
					DiscountAmount decimal(12, 2),
					IsChequeCleared bit,
					ChequeClearDate date,
					ChequeDate date, 
					FeeInvoiceId bigint,
					CollectionGroupId int
					)A
		INNER JOIN sStudent.tAcademic FS On fs.Id=A.SourceId
		Where FS.DivisionId=@rDivisionId
					
	  END	
	
	 SELECT 1 AS Result
		COMMIT TRANSACTION
		END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sSetup].[pPortalReceiptBookMasterAdd]...';


GO
 
 
CREATE PROCEDURE [sSetup].[pPortalReceiptBookMasterAdd]
	
	@rStrXml nvarchar(MAX),
    @rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 
	 
	 EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
	 
	 DELETE   FROM sFee.tReceiptBookMaster WHere OrgGroupId=@rOrgGroupId
	 
	 INSERT INTO sFee.tReceiptBookMaster
		(
			OrgGroupId,
			Id,
			Code,
			Title,
			FullTitle,
			 Address1,
			 Address2,
			 BankAccountNumber,
			 CreatedUserId,
			 CreatedDateTime,
			 IsObsolete,
			 UpdatedUserId,
			 UpdatedDateTime,
			 Remark1,
			 Remark2,
			 IsOnPrePrinted,
			 ReportId,
			 IsSupressLogo,
			 OrderIndex,
			 IsDisplaySchoolName,
			 IsMonthDetailOnly,
			 IsServiceTaxApplicable,
			 ServiceTaxPercentage,
			 BankName,
			 IsFeeInvoiceHeadwise,
			 GroupTitle,
			 IsSuppressFeeDetail,
			 ReceiptLogo,
			 ReceiptBookHeader,
			 HeaderDisplayId,
			 FeeInvoiceHeader,
			 FeeInvoiceHeaderDisplayId
			)
		SELECT		
			 OrgGroupId,
			Id,
			Code,
			Title,
			FullTitle,
			Address1,
			Address2,
			BankAccountNumber,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			UpdatedUserId ,
			UpdatedDateTime,
			Remark1,
			Remark2,
			IsOnPrePrinted,
			ReportId,
			IsSupressLogo,
			OrderIndex,
			IsDisplaySchoolName,
			IsMonthDetailOnly,
			IsServiceTaxApplicable,
			ServiceTaxPercentage,
			BankName,
			IsFeeInvoiceHeadwise,
			GroupTitle,
			IsSuppressFeeDetail,
			ReceiptLogo,
			ReceiptBookHeader,
			HeaderDisplayId,
			FeeInvoiceHeader,
			FeeInvoiceHeaderDisplayId
		
		FROM OPENXML (@loDoc, '/Table/ReceiptBookMaster', 1)
		WITH ( 
				OrgGroupId smallint,
				Id int,
			    Code nvarchar(20),
			    Title nvarchar(100),
			    FullTitle nvarchar(200),
			    Address1 nvarchar(200),
			    Address2 nvarchar(200),
			    BankAccountNumber nvarchar(50),
			    CreatedUserId bigint,
			    CreatedDateTime datetime,
			    IsObsolete bit,
			    UpdatedUserId bigint,
			    UpdatedDateTime datetime,
			    Remark1 nvarchar(500) ,
			    Remark2 nvarchar(500),
			    IsOnPrePrinted bit,
			    ReportId int,
			    IsSupressLogo bit,
			    OrderIndex int,
			    IsDisplaySchoolName bit,
			    IsMonthDetailOnly bit,
			    IsServiceTaxApplicable bit,
			    ServiceTaxPercentage decimal(6,2),
			    BankName nvarchar(150),
			    IsFeeInvoiceHeadwise bit,
			    GroupTitle nvarchar(200),
			    IsSuppressFeeDetail bit,
			    ReceiptLogo varbinary(max),
			    ReceiptBookHeader varbinary(max),
			    HeaderDisplayId tinyint,
			    FeeInvoiceHeader varbinary(max),
			    FeeInvoiceHeaderDisplayId tinyint
			  )  
		--EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalReceiptBookOrgwiseAdd]...';


GO
 
 
CREATE PROCEDURE [sSetup].[pPortalReceiptBookOrgwiseAdd]
	
	@rStrXml nvarchar(MAX) ,
	@rOrgId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE  FROM sFee.tReceiptBookOrgwise WHERE OrgId=@rOrgId
	 
	 INSERT INTO sFee.tReceiptBookOrgwise
		(
			OrgId,
			ReceiptBookId  
			)
		SELECT		
			OrgId,
			 ReceiptBookId 
			  
		FROM OPENXML (@loDoc, '/Table/ReceiptBookOrgwise', 1)
		WITH ( 
				OrgId smallint,
				ReceiptBookId int 
			  )  
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalReceiptDetailAdd]...';


GO
 
 
 
CREATE PROCEDURE [sSetup].[pPortalReceiptDetailAdd]
	
	@rStrXml nvarchar(MAX),
	@rDivisionId int
   
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT,@lCount int 
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	 BEGIN TRY
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 Update  sFee.tReceiptDetail
	 Set 
			ReceiptId=A.ReceiptId,
			FeeSetupId=A.FeeSetupId,
			Amount=A.Amount
	From
	(
	  SELECT		
			ReceiptId,
			FeeSetupId,
			Amount 
		
		FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				
			   ReceiptId bigint,
				FeeSetupId int,
				Amount decimal(12, 2) 
			  ) 
	  )A 
	  INNER JOIN sFee.tReceipt RT ON RT.Id=A.ReceiptId
	  INNER JOIN sStudent.tAcademic AB ON RT.SourceId=AB.Id
	  
	   Where sFee.tReceiptDetail.ReceiptId=A.ReceiptId AND AB.DivisionId=@rDivisionId
	  
			  
	  INSERT INTO sFee.tReceiptDetail
		(
			ReceiptId,
			FeeSetupId,
			Amount 
			)
		SELECT		
			A.ReceiptId,
			A.FeeSetupId,
			A.Amount 
		
		FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				
			   ReceiptId bigint,
				FeeSetupId int,
				Amount decimal(12, 2) 
			  )A
	INNER JOIN sFee.tReceipt RT ON RT.Id=A.ReceiptId
	INNER JOIN sStudent.tAcademic  AB On RT.SourceId=AB.Id
	Where AB.DivisionId=@rDivisionID
		
	 
        SELECT 1 AS Result
	  END	
	
	
		COMMIT TRANSACTION
		END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sSystem].[pBackupLogAdd]...';


GO
CREATE PROCEDURE [sSystem].[pBackupLogAdd]
        
        @rBackupPath nvarchar(200)='',
        @rCreatedUserId bigint=0
        
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	DECLARE @lVersionId bigint=0
	SELECT @lVersionId = VersionId FROM sSystem.tDatabaseInfo
	
	INSERT INTO sSystem.tBackupLog
		(
			BackupDateTime,
			BackupPath,
			VersionId,
			CreatedUserId 
		)
	VALUES
		(
			sCommon.fGetDate(),	
			@rBackupPath,
			@lVersionId,
			@rCreatedUserId
		)
		
	    SELECT 1 AS Result
	    
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSystem].[pDatabaseRestore]...';


GO
CREATE procedure [sSystem].[pDatabaseRestore]
@SourceDBName varchar(250),
@TargetDBName varchar(250),
@TargetPath varchar(250)
as

DECLARE @SourceDatabaseName varchar(200)
DECLARE @SourceDatabaseLogicalName varchar(200)
DECLARE @SourceDatabaseLogicalNameForLog varchar(200)
DECLARE @query varchar(2000)
DECLARE @DataFile varchar(2000)
DECLARE @LogFile varchar(2000)
DECLARE @BackupFile varchar(2000)
DECLARE @TargetDatabaseName varchar(200)
DECLARE @TargetDatbaseFolder varchar(2000)


SET @SourceDatabaseName = @SourceDBName                 
SET @BackupFile = @TargetPath + '\backup.dat'
SET @TargetDatabaseName = @TargetDBName 
SET @TargetDatbaseFolder = @TargetPath

SET @DataFile = @TargetDatbaseFolder + Replace(Replace(@TargetDatabaseName,'[',''),']','') + '.mdf';
SET @LogFile = @TargetDatbaseFolder + Replace(Replace(@TargetDatabaseName,'[',''),']','') + '.ldf';

SET @query = 'del ' + @BackupFile 
EXEC xp_cmdshell @query

IF @SourceDatabaseName IS NOT NULL
BEGIN
SET @query = 'BACKUP DATABASE ' + @SourceDatabaseName + ' TO DISK = ' + QUOTENAME(@BackupFile,'''')
PRINT 'Executing query : ' + @query;
EXEC (@query)
END
PRINT 'OK!';

DECLARE @Table TABLE (LogicalName varchar(128), Physical_Name varchar(200))
INSERT INTO @table
   select name,Physical_Name from    sys.master_files where   database_id = db_id(Replace(Replace(@SourceDBName,'[',''),']',''))
   SET @SourceDatabaseLogicalName=(SELECT LogicalName FROM @Table WHERE LogicalName LIKE '%DATA%')
   SET @SourceDatabaseLogicalNameForLog=(SELECT LogicalName FROM @Table WHERE LogicalName LIKE '%LOG%')


IF EXISTS(SELECT * FROM sysdatabases WHERE name = @TargetDatabaseName)
BEGIN
SET @query = 'DROP DATABASE ' + @TargetDatabaseName
PRINT 'Executing query : ' + @query;
EXEC (@query)
END
PRINT 'OK!'

SET @query = 'RESTORE DATABASE ' + @TargetDatabaseName + ' FROM DISK = ' + QUOTENAME(@BackupFile,'''') 
SET @query = @query + ' WITH MOVE ' + QUOTENAME(@SourceDatabaseLogicalName,'''') + ' TO ' + QUOTENAME(@DataFile ,'''')
SET @query = @query + ' , MOVE ' + QUOTENAME(@SourceDatabaseLogicalNameForLog,'''') + ' TO ' + QUOTENAME(@LogFile,'''')
PRINT 'Executing query : ' + @query
EXEC (@query)
PRINT 'OK!'
GO
 
  
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('17.09.02',170902,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO