

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

PRINT N'Dropping Procedure [sEMeeting].[pbatchmasterGet]...';


GO
DROP PROCEDURE [sEMeeting].[pbatchmasterGet];


GO
PRINT N'Altering Table [sAttendance].[tYearlyRegister]...';


GO
ALTER TABLE [sAttendance].[tYearlyRegister]
    ADD [AttendanceTypeId] TINYINT CONSTRAINT [DF_tYearlyRegister_AttendanceTypeId] DEFAULT ((1)) NULL;


GO
PRINT N'Altering View [sCertificate].[vPrintTemplateLeavingCertificate]...';


GO


ALTER VIEW [sCertificate].[vPrintTemplateLeavingCertificate]
AS  
	SELECT 
		L.Id,
		SM.Code,
		L.AcademicId,
		SM.FirstName,SM.MiddleName,SM.LastName,
		[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
		ISNULL(SF.FatherName,'') As FatherName,
		ISNULL(SF.MotherName,'') As MotherName,
		ISNULL(CTM.Nationality,'') AS Nationality,
		ISNULL(RM.Title,'') AS Religion,
		ISNULL(so.BirthPlace,'') AS BirthPlace,
		ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
		ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
		SO.DateOfBirth,
		ISNULL(SO.BirthDateInWord,'') AS DOBInWord,
		SA.PreviousSchool,
		SA.AdmissionDate,
		L.LCNumber,
		L.LeftDate,
		L.LCReason,
		L.LCProgress,
		L.LCConduct,
		L.LCRemark,
		L.LCDate,
		L.LCBookNumber,
		SO.GenderId,
		ISNULL(SO.FamilySubCast,'') AS SubCaste,
		ISNULL(SO.FamilyCast,'') AS Caste,
		ISNULL(OM.CityName,'') AS City,
		ISNULL(OM.StateName,'') AS CityState,
		CM.DisplayTitle AS AdmissionStandard,
		CMS.DisplayTitle AS CurrentStandard,
		CMS.Title AS CurrentStandardTitle,
		SM.StatusId,
		L.LastExamName AS Result,
		L.LastExamResult AS FailOrPass,
		L.SubjectStudied AS SubjectNAme,
		L.RepeatDetail as PromotedorNot,
		L.PromoteToClass  AS PromotedToClass,
		L.FeeDetail AS LastFeesPaid,
		L.FeeConcessionDetail AS AnyConcession,
		L.NCCScoutDetail  AS NCCScoutDetail,
		L.ExtraCurricularActivities AS GamesPlayed,
		OM.OrgLogo,
		OM.Title AS OrgTitle,
		OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
		OM.PhoneNo,
		vSA.RollNo,
		DM.OrderIndex AS DivisionOrder,
		OM.SmallAddress1,
		OM.SmallAddress2,
		OM.RegistrationDetail,
		AD.PresentDaysAnnual AS PresentDaysSum,
		AD.TotalDaysAnnual AS TotalDaysSum,
		vSA.ClassName AS ClassName,
		vSA.DivisionName AS DivisionName,
		OI.CertificateHeaderA4  ,
		isnull(MainCastCategoryId,0) AS CastCategoryId,
		ISNULL(L.ToCollege,'') AS ToCollege ,
		ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
		ISNULL(OM.University,'')AS University,
		ISNULL(CSG.Inword,'')AS CurrentStandardInWords,
		SO.MotherTongue,
		SO.AdhaarNumber,
		vSA.SUId,
		CASE WHEN isnull(BM.FromDate,'')>Isnull(SA.AdmissionDate,'') THEN BM.FromDate ELSE SA.AdmissionDate END AS BatchDate,
		SO.BirthState,
		SO.BirthCountry,
		SD.BankAccountNumber,
		SO.UIDNumber,
		SD.BankName,
		SD.BankIFSCCode,
		SA.PreviousStandard ,
		L.TermsInInstitute,
		L.LCCopy,
		DM.InchargeEmployeeId AS ClassTeacher,
		vSA.BatchName AS BatchName,
		CSM.Title As CasteCategory,	
		vSA.BatchId,
		GetDate() AS PrintDate, -- Change for Mantis id 29447 and also added in below row "[PrintDate]"
		'[AdhaarNumber],[AdmissionDate],[AdmissionStandard],[AnyConcession],[BankAccountNumber],[BankIFSCCode],[BankName],[BatchDate],[BatchName],[BirthCountry],[DOBInWord],[BirthDistrict],[BirthPlace],[BirthState],[BirthTaluka],[Caste],[CasteCategory],[CertificateHeaderA4],[City],[CityState],[ClassName],[ClassTeacher],[Code],[CurrentStandard],[CurrentStandardInWords],[CurrentStandardTitle],[DateOfBirth],[DivisionName],[DivisionOrder],[FailOrPass],[FatherName],[FirstName],[GamesPlayed],[LastFeesPaid],[LastName],[LCBookNumber],[LCConduct],[LCCopy],[LCDate],[LCNumber],[LCProgress],[LCReason],[LCRemark],[LeftDate],[MiddleName],[MotherName],[MotherTongue],[Name],[Nationality],[NCCScoutDetail],[OrgAddress],[OrgLogo],[OrgTitle],[PhoneNo],[PresentDaysSum],[PreviousSchool],[PreviousStandard],[PromotedorNot],[PromotedToClass],[RegistrationDetail],[Religion],[Result],[RollNo],[SmallAddress1],[SmallAddress2],[SubCaste],[SubjectNAme],[TermsInInstitute],[ToCollege],[ToCollegeAddress],[TotalDaysSum],[UIDNumber],[University],[PrintDate]' As ColumnList
	FROM 
		sCertificate.tLeaving L
		INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
		LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
		LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
		INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
		INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
		LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
		LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
		LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
GO
PRINT N'Altering View [sCertificate].[vPrintTemplateStudentBasicDetails]...';


GO


ALTER VIEW [sCertificate].[vPrintTemplateStudentBasicDetails]
AS
	SELECT 
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS StudentName,
	  SM.Code,	
	  DM.Code AS ClassDivision,
	  A.RollNo,
	  BM.Title AS BatchName,
	  SO.DateOfBirth AS DateOfBirth, 
	  GetDate() AS PrintDate, 	-- Change for Mantis id 29447 and also added in below row "[PrintDate]" 
	  '[BatchName],[ClassDivision],[Code],[DateOfBirth],[RollNo],[FirstName],[MiddleName],
	  [LastName],[PreviousSchool],[Gender],[Caste],[SubCaste],[BirthPlace],[DOBInWords],[PreviousSchoolYear],
	  [OldGRNo],[PreviousLCDate],[PreviousLCResult],[PreviousLCNumber],[PreviousStandard],
	  [BirthTaluka],[BirthState],[BirthCountry],[BirthDistrict],[Address],[ContactNo],[Email],[Religion],[FamilyCaste],[CasteCategory],[Nationality],[MotherTongue],[BloodGroup],[AadhaarNumber],[PhysicalCategory],
	  [FatherName],[FatherQualification],[FatherOccupation],[FatherContactNo],[FatherOfficeAddress],[FatherEmail],[FatherExStudent],[FatherPassingYear],[FatherIncome],
	  [MotherName],[MotherQualification],[MotherOccupation],[MotherContactNo],[MotherOfficeAddress],[MotherEmail],[MotherExStudent],[MotherPassingYear],[MotherIncome],
	  [AdmissionDate],[AdmissionStandard],[ClassName],[UIDNumber],[BankHolderName],[BankName],[BankBranch],[BankIFSCcode],[BankAccountNo],[StudentPhoto],[WhatsAppContactNo],[PrintDate]' As ColumnList
  FROM 
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id
	INNER JOIN sStudent.tStudentAdmission SA
		ON SA.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId
	INNER JOIN sSetup.tDepartmentMaster DeptM
		ON DeptM.Id=CM.DepartmentId
	INNER JOIN sSetup.tOrganizationMaster OM 
	    ON A.OrgId = OM.Id
	INNER JOIN [sStudent].[tStudentOther] SO
	    ON SO.StudentId=SM.Id
GO
PRINT N'Altering View [sCertificate].[vPrintTemplateStudentDetail]...';


GO


ALTER VIEW [sCertificate].[vPrintTemplateStudentDetail]
 
AS  
  
SELECT 
			A.Id AS AcademicId,
		    DivM.Id AS DivisionId,
		    DivM.DisplayTitle AS DivisionName,
		    CM.Id AS ClassId,
		    CM.DisplayTitle AS ClassName,
		    CM.DisplayTitle+'-'+DivM.DisplayTitle AS ClassDivision,
		    DM.Id AS DepartmentId,
		    DM.DisplayTitle AS DepartmentName,
		    SM.FirstName AS FirstName,
		    SM.MiddleName AS MiddleName,
		    SM.LastName AS LastName,
		    SM.Code,
		    A.RollNo,
		    A.BatchId,
		    BM.Title AS BatchName,
		    CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
		    SA.PreviousSchool,
			ISNULL(GM.Title,'') AS Gender,
			SO.FamilyCast AS Caste,  
			SO.FamilySubCast AS SubCaste,
			SO.BirthPlace,
			SO.BirthDateInWord AS DOBInWords,
			SA.PreviousLCDate AS PreviousLCDate,
			SA.PreviousLCResult AS PreviousLCResult,
			SA.PreviousLCNumber AS PreviousLCNumber,
			SA.AdmissionNumber AS OldGRNo,
			SA.PassingYear AS PreviousSchoolYear,			
			SA.PreviousStandard AS PreviousStandard,
			SO.BirthTaluka AS BirthTaluka,
			SO.BirthState AS BirthState,
			SO.BirthCountry AS BirthCountry,
			SO.BirthDistrict AS BirthDistrict,
			ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS Address,
			SC.ParentContactNo AS ContactNo,		
			SC.ParentEmail AS Email,
			ISNULL(RM.Title,'') AS Religion,
			SO.FamilyCast AS FamilyCaste,
			ISNULL(CCM.Title,'') AS CasteCategory,
			ISNULL(NM.Title,'') AS Nationality,
			ISNULL(SO.MotherTongue,'') AS MotherTongue,
			ISNULL(BGM.Title,'') As BloodGroup,
			ISNULL(SO.AdhaarNumber,'') AS AadhaarNumber,
			ISNULL(PDCM.Title,'') AS PhysicalCategory,
			SF.FatherName AS FatherName,
			SF.FatherQualification AS FatherQualification,
			SF.FatherOccupation AS FatherOccupation,
			SF.FatherContactNo AS FatherContactNo,
			SF.FatherOfficeAddress AS FatherOfficeAddress,
			SF.FatherMail AS FatherEmail,
			SF.IsFatherExStudent AS FatherExStudent,
			SF.FatherPassOutYear AS FatherPassingYear,
			SF.FatherIncome AS FatherIncome,
			SF.MotherName AS MotherName,
			SF.MotherQualification AS MotherQualification,
			SF.MotherOccupation AS MotherOccupation,
			SF.MotherContactNo AS MotherContactNo,
			SF.MotherOfficeAddress AS MotherOfficeAddress,
			SF.MotherMail AS MotherEmail,
			SF.IsMotherExStudent AS MotherExStudent,
			SF.MotherPassOutYear AS MotherPassingYear,
			SF.MotherIncome AS MotherIncome,
			SA.AdmissionDate AS AdmissionDate,
			CM1.Title AS AdmissionStandard,
			SO.UIDNumber AS UIDNumber,
			ISNULL(StuA.BankAccountHolderName,'') AS BankHolderName,
			ISNULL(StuA.BankName,'') AS BankName,
			ISNULL(StuA.BankBranch,'') AS BankBranch,
			ISNULL(StuA.BankIFSCcode,'') AS BankIFSCcode,
			ISNULL(StuA.BankAccountNumber,'') AS BankAccountNo,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			GetDate() AS PrintDate -- Change for Mantis id 29447 added "[PrintDate]"

	FROM 
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DivM ON DivM.Id=A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = A.StudentId
			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 sCommon.tMotherTongueMaster MT ON MT.Id = SO.MotherTongueId
			LEFT JOIN sCommon.tCountryMaster NM ON NM.Id = SO.NationalityId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId
			LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId = A.StudentId
			LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id=SA.AdmissionStandardId
			LEFT JOIN sStudent.tStudentAdditional StuA ON StuA.StudentId = SM.Id
			LEFT JOIN sStudent.tStudentImages SI ON SM.Id = SI.StudentId
GO
PRINT N'Altering View [sStudent].[vStudentVerification]...';


GO
 
 
ALTER VIEW [sStudent].[vStudentVerification]  
  
AS  
 
SELECT 
	  A.Id AS AcademicId,	  
	  A.ClassId,
	  A.DivisionId,
	  A.RollNo,
	  A.OrgId,
	  A.BatchId,
	  SM.Id AS StudentId,
	  SM.Code,
	  ISNULL(SM.Number,0) AS Number,
	  SM.RegistrationNumber,
	  SM.FirstName,
	  SM.MiddleName,
	  SM.LastName,
	    SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,	   
	  SM.RecordStatusId,	  
	  DM.InchargeEmployeeId, 
	  BM.OrgGroupBatchId,	  
	  SM.AdmissionCategoryId,
	  DM.OrderIndex DivisionOrder,
	  BM.IsActive AS IsActiveBatch,
	  BM.Title AS BatchName,
	  SM.IsBlackList,
	  SM.BlackListReason,
	  CM.OrderIndex AS ClassOrderIndex,
	  ISNULL(A.ExemptionTypeId,0) AS ExemptionTypeId,
	  ISNULL(SM.SUId,'') AS SUId ,
	  SA.AdmissionDate,
	  SA.PreviousSchool,
	  SO.DateOfBirth,
	  SO.BirthPlace,
	  GEN.Title As Gender,
	  SO.FamilyCast,
	  CC.Title As CastCatagory,
	  SO.MotherTongue,
	  --NM.Title AS Nationality,
	  SF.FatherName,
	 SF.FatherContactNo,
	 sf.MotherName,
	 SF.MotherContactNo,
	 SC.PresentStreetOne,
	 SC.PresentStreetTwo,
	 SC.PresentStreetThree,
	 SC.StudentContactNo,
	 SO.UIDNumber,
	 SO.AdhaarNumber,
	 STA.BankBranch,
	 STA.BankAccountNumber,
	 STA.BankName,
	 STA.BankIFSCCode,
	Dept.ID as DepartmentId,
	  SA.ADMISSIONStandardId,
	  NM.OrgGroupId,
	   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	   R.Title As Religion,
	   SC.StudentEmail,
	   CON.Nationality,
	   SO.BirthState,
	   SO.BirthCountry,
	   SO.BirthTaluka,
	   SO.BirthDistrict,
	   STA.BankAccountHolderName,	   
	   SF.MarriageAnniversaryDate
	  
  FROM 
	sStudent.tAcademic A 
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
	 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentID=SM.Id   
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SM.Id
	INNER JOIN sCommon.tGenderMaster GEN ON GEN.Id=SO.GenderId
	LEFT JOIN sCommon.tCastCategoryMaster CC oN CC.Id=SO.CastCategoryId
	LEFT JOIN sCommon.tCountryMaster NM ON NM.Id=SO.NationalityId 
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =SM.Id
	LEFT JOIN sStudent.tStudentAdditional STA ON STA.StudentId=Sm.Id
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=Cm.DepartmentId
	LEFT JOIN sCommon.tReligionMaster R ON R.id=SO.ReligionId
 INNER JOIN sSetup.tOrganizationMaster OM
	    ON SM.OrgId = OM.Id
	LEFT JOIN sCommon.tCountryMaster CON ON CON.ID = SO.NationalityID
GO
PRINT N'Altering Function [sHrm].[fEmployeeWiseAttendanceJoiningDateGet]...';


GO
ALTER FUNCTION [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](@rEmployeeId bigint, @rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDepartmentId int,@rOrgId int,@rAttendanceDate nvarchar(20), @rDateOfJoining date,@rDateOfLeaving date,@rStatus nvarchar(10))
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN	

	DECLARE @lWeekOff nvarchar(20)
	Declare @WeekNumber int,@EmpSecondWeekOffRule int,@EmpFirstWeekOffRule int
	DECLARE @lDate datetime,@lWeekDay1 nvarchar(20),@lWeekDay2  nvarchar(20)
	DECLARE @lCOUNT int 
	DECLARE @lEmployeeFirstWeekOffDayId int
	DECLARE @lEmployeeSEcondWeekOffDayId int
	DECLARE @lEmployeeFirstWeekOffRuleId int
	DECLARE @lEmployeeSecondWeekOffRuleId int



	SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @rDay)
	SET @lWeekOff = [sAssessment].[fGetdayNumber](@lDate)
	Set @WeekNumber = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @lDate), 0)), 0), @lDate)+1

	SET @lEmployeeFirstWeekOffDayId= (SELECT EmployeeFirstWeekOffDayId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
	SET @lEmployeeSEcondWeekOffDayId= (SELECT EmployeeSEcondWeekOffDayId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
	SET @lEmployeeFirstWeekOffRuleId= (SELECT EmployeeFirstWeekOffRuleId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
	SET @lEmployeeSecondWeekOffRuleId= (SELECT EmployeeSecondWeekOffRuleId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 



	IF ((@lEmployeeFirstWeekOffDayId !=0 AND @lEmployeeFirstWeekOffRuleId !=0 ) OR (@lEmployeeSEcondWeekOffDayId != 0 AND @lEmployeeSecondWeekOffRuleId!=0))
	BEGIN
		SELECT @lWeekDay1 = EmployeeFirstWeekOffDayId,@lWeekDay2 = EmployeeSEcondWeekOffDayId,@EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId,@EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId  FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId 
	END 	
	ELSE
	BEGIN
		SELECT @lWeekDay1 = FirstWeekOffDayId, @lWeekDay2 = SecondWeekOff,@EmpFirstWeekOffRule = FristWeekOffRuleId,@EmpSecondWeekOffRule = SEcondWeekOffRuleId FROM sActivity.tWeekOffSetting  WHERE SourceId = @rEmployeeId AND SourceTypeId=95	
	END

	IF @EmpFirstWeekOffRule = 1 
	BEGIN		
		IF(@lWeekOff = @lWeekDay1)
		BEGIN	
				
			Set @rStatus = 'W'
			RETURN @rStatus	
		END 					
		IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
		BEGIN 
				SET @rStatus = 'P'
		END
		IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
		BEGIN 						
				SET @rStatus = 'A'
		END		
		IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id			
					WHERE ES.BatchId = @rBatchId 
					AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
					AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus		
		END
	END
				
	Else if @EmpFirstWeekOffRule = 2 
	BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			    SET @rStatus = 'H'	
				RETURN @rStatus		
		    END
		END	 
	END
	Else if @EmpFirstWeekOffRule = 3 
	BEGIN
		IF @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			    SET @rStatus = 'H'	
				RETURN @rStatus		
		    END
		END 
	END
	else if @EmpFirstWeekOffRule = 4
	BEGIN 
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'	
				RETURN @rStatus	
			END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	Else if @EmpFirstWeekOffRule = 5 
	BEGIN   
		IF @WeekNumber = 2 or @WeekNumber = 3 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			        SET @rStatus = 'H'	
			RETURN @rStatus		
		    END
		END
	END
	
	Else if @EmpFirstWeekOffRule = 6 
	BEGIN	   
		IF @WeekNumber = 1 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus		
			END			 
		END 
	END
	
	Else if @EmpFirstWeekOffRule = 7 
	BEGIN  
		IF @WeekNumber = 2 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			    SET @rStatus = 'H'	
				RETURN @rStatus		
		    END
		END
	END
	
	Else if @EmpFirstWeekOffRule = 8 
	BEGIN  
		IF @WeekNumber = 3 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus		
			END 
		END
	END
	Else if @EmpFirstWeekOffRule = 9 
	BEGIN
		IF @WeekNumber = 4 
		BEGIN			
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95) 
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus		
			END	 
		END		 
	END	
	--Add EmpFirstWeekOffRule = 10 due to mantisid - 0028624
	else if @EmpFirstWeekOffRule = 10
	BEGIN 
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'	
				RETURN @rStatus	
			END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	if @EmpSecondWeekOffRule = 1 
	BEGIN	 
		if(@lWeekOff = @lWeekDay2)
		BEGIN
			Set @rStatus = 'W'
			RETURN @rStatus	
		END
		if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
		BEGIN 
			SET @rStatus = 'P'
		END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
		BEGIN 
			SET @rStatus = 'A'
		END	
		IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
		WHERE ES.BatchId = @rBatchId 
		AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
		--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
		--AND SourceTypeId in (95)
		AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		BEGIN
			SET @rStatus = 'H'	
			RETURN @rStatus	
		END
	END
	Else if @EmpSecondWeekOffRule = 2 
	BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END	
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			-- AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	else if @EmpSecondWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'		
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	else if @EmpSecondWeekOffRule = 4
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	Else if @EmpSecondWeekOffRule = 5
	BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	Else if @EmpSecondWeekOffRule = 6
	BEGIN
		IF @WeekNumber = 1 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END		
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	Else if @EmpSecondWeekOffRule = 7
	BEGIN
		IF @WeekNumber = 2 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
					
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				WHERE ES.BatchId = @rBatchId 
				AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
				--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
				--AND SourceTypeId in (95)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	
	Else if @EmpSecondWeekOffRule = 8
	BEGIN
		IF @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END	
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				WHERE ES.BatchId = @rBatchId 
				AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
				--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
				--AND SourceTypeId in (95)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END	 
		END
	END
	
	Else if @EmpSecondWeekOffRule = 9
	BEGIN
		IF @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END		
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				WHERE ES.BatchId = @rBatchId
				AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
				-- AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
				--AND SourceTypeId in (95)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END 
	END
	--Add EmpSecondWeekOffRule = 10 due to mantisid - 0028624
	else if @EmpSecondWeekOffRule = 10
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
			END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END

	--add for 29237 mantis if condition
	--It Take assign Holiday acording to SourcetypeId
	IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				WHERE ES.BatchId = @rBatchId
					AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
					--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
					--AND SourceTypeId in (95)
					AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
	BEGIN
		SET @rStatus = 'H'	
		RETURN @rStatus	
	END

	if(@rDateOfJoining IS NOT NULL AND @rDateOfLeaving IS NOT NULL)
		Set @ldate = @rAttendanceDate	
	if ISDATE(@ldate)=1	
	BEGIN
		if(@rDateOfJoining  > @rAttendanceDate)
		BEGIN
			SET @rStatus = 'NA' 
			RETURN @rStatus
		END
		IF(@rDateOfLeaving<>'')
		BEGIN
			if(@rDateOfLeaving <= @rAttendanceDate)
			BEGIN
				SET @rStatus='L'
				RETURN @rStatus
			END
		END
	END
	IF(@rStatus Is NULL)
		SET @rStatus = ''
	RETURN @rStatus
END
GO
PRINT N'Creating Function [sAlert].[fResultGetWithLineBreak]...';


GO

 
CREATE FUNCTION [sAlert].[fResultGetWithLineBreak](@rResultId bigint,@rSubjectId int, @rTypeId tinyint)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult  VARCHAR(MAX)

IF(@rTypeId=1)
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CHAR(13) + CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - ' +
			(
			CASE  
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab , '
			WHEN  E.IsMarksInDecimal = 1 then
			CONVERT(VARCHAR(11),RD.Obtain)
			WHEN E.IsMarksInDecimal = 0 then
			CONVERT(VARCHAR(11),CAST(RD.Obtain AS INT)) 
			END)
			    + ' , ' 
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		 
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END
ELSE
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+  CHAR(13) + CONVERT(VARCHAR(11),CS.SubjectCode,106) + ' - ' +
			(
			CASE  
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab'
			ELSE
			ISNULL(RD.SubjectGrade,'') 
			END)
			    + ' , ' 
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		 
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END
    RETURN @lResult 
END
GO
PRINT N'Creating Function [sAlert].[fResultWithMaxGetWithLineBreak]...';


GO

CREATE FUNCTION [sAlert].[fResultWithMaxGetWithLineBreak](@rResultId bigint,@rSubjectId int)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult  VARCHAR(MAX)
(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CHAR(13) + CONVERT(VARCHAR(11),CS.SubjectCode,106) + ' - ' +
			(
			CASE 
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab , '
			WHEN E.IsMarksInDecimal = 1 THEN  CONVERT(VARCHAR(11),RD.Obtain)
			else CONVERT(VARCHAR(11),CAST(RD.Obtain AS INT))END)
			+(CASE 
			WHEN RD.IsPresent = 0 THEN ''
			WHEN RD.IsPresent != 0 THEN + ' / ' + CONVERT(VARCHAR(11),Cast(Round(ED.Maximum,0) AS int)) + ' , ' END)
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult)- 1)
    RETURN @lResult 
END
GO
PRINT N'Altering Procedure [sAttendance].[pYearlyRegisterGet]...';


GO
ALTER PROCEDURE [sAttendance].[pYearlyRegisterGet]

	 
	 @rAcademicId bigint=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int=0,
	 @rAttendanceTypeId tinyint=0,
	 @rStatus int=0,
	 @rDepartmentId int=0,
	 @rStudentCode nvarchar(20) = '',
	 @rBuilder1 nvarchar(max)='',		--add for mantis 27006
	 @rBuilder2 nvarchar(max)=''		--add for mantis 27006

	
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
DECLARE @Month1 nvarchar(20),@Month2 nvarchar(20),@Month3 nvarchar(20),
        @Month4 nvarchar(20),@Month5 nvarchar(20),@Month6 nvarchar(20),
		@Month7 nvarchar(20),@Month8 nvarchar(20),@Month9 nvarchar(20),
		@Month10 nvarchar(20),@Month11 nvarchar(20),@Month12 nvarchar(20)
	 
	 Select @Month1 = Month1 FROM sAttendance.tYearlyRegister WHERE Month1 IS NOT NULL
	 Select @Month2 = Month2 FROM sAttendance.tYearlyRegister WHERE Month2 IS NOT NULL
	 Select @Month3 = Month3 FROM sAttendance.tYearlyRegister WHERE Month3 IS NOT NULL
	 Select @Month4 = Month4 FROM sAttendance.tYearlyRegister WHERE Month4 IS NOT NULL
	 Select @Month5 = Month5 FROM sAttendance.tYearlyRegister WHERE Month5 IS NOT NULL
	 Select @Month6 = Month6 FROM sAttendance.tYearlyRegister WHERE Month6 IS NOT NULL
	 Select @Month7 = Month7 FROM sAttendance.tYearlyRegister WHERE Month7 IS NOT NULL
	 Select @Month8 = Month8 FROM sAttendance.tYearlyRegister WHERE Month8 IS NOT NULL
	 Select @Month9 = Month9 FROM sAttendance.tYearlyRegister WHERE Month9 IS NOT NULL
	 Select @Month10 = Month10 FROM sAttendance.tYearlyRegister WHERE Month10 IS NOT NULL
	 Select @Month11 = Month11 FROM sAttendance.tYearlyRegister WHERE Month11 IS NOT NULL
	 Select @Month12 = Month12 FROM sAttendance.tYearlyRegister WHERE Month12 IS NOT NULL

        
SELECT 
	A.Id AS AcademicId,
	A.RollNo,
	SM.Code,
	ISNULL(YR.AvergeAttendance,0) AS AvergeAttendance,
	YR.TotalDays,
	YR.PresentDays,
	
	ISNULL(YR.Month1,@Month1) AS Month1,
	ISNULL(YR.PresentDays1,0) AS PresentDays1,
	ISNULL(YR.TotalDays1,0) AS TotalDays1,
	
	ISNULL(YR.Month2,@Month2) AS Month2,
	ISNULL(YR.PresentDays2,0) AS PresentDays2,
	ISNULL(YR.TotalDays2,0) AS TotalDays2,
	
	ISNULL(YR.Month3,@Month3) AS Month3,
	ISNULL(YR.PresentDays3,0) AS PresentDays3,
	ISNULL(YR.TotalDays3,0) AS TotalDays3,
	
	ISNULL(YR.Month4,@Month4) AS Month4,
	ISNULL(YR.PresentDays4,0) AS PresentDays4,
	ISNULL(YR.TotalDays4,0) AS TotalDays4,
	
	ISNULL(YR.Month5,@Month5) AS Month5,
	ISNULL(YR.PresentDays5,0) AS PresentDays5,
	ISNULL(YR.TotalDays5,0) AS TotalDays5,
	
	ISNULL(YR.Month6,@Month6) AS Month6,
	ISNULL(YR.PresentDays6,0) AS PresentDays6,
	ISNULL(YR.TotalDays6,0) AS TotalDays6,
	
	ISNULL(YR.Month7,@Month7) AS Month7,
	ISNULL(YR.PresentDays7,0) AS PresentDays7,
	ISNULL(YR.TotalDays7,0) AS TotalDays7,
	
	ISNULL(YR.Month8,@Month8) AS Month8,
	ISNULL(YR.PresentDays8,0) AS PresentDays8,
	ISNULL(YR.TotalDays8,0) AS TotalDays8,
	
	ISNULL(YR.Month9,@Month9) AS Month9,
	ISNULL(YR.PresentDays9,0) AS PresentDays9,
	ISNULL(YR.TotalDays9,0) AS TotalDays9,
	
	ISNULL(YR.Month10,@Month10) AS Month10,
	ISNULL(YR.PresentDays10,0) AS PresentDays10,
	ISNULL(YR.TotalDays10,0) AS TotalDays10,
	
	ISNULL(YR.Month11,@Month11) AS Month11,
	ISNULL(YR.PresentDays11,0) AS PresentDays11,
	ISNULL(YR.TotalDays11,0) AS TotalDays11,
	
	ISNULL(YR.Month12,@Month12) AS Month12,
	ISNULL(YR.PresentDays12,0) AS PresentDays12,
	ISNULL(YR.TotalDays12,0) AS TotalDays12,
	
	SM.FirstName + ' ' + ' '+ SM.MiddleName+ ' ' + SM.LastName As Name,	
	SM.StatusID,
	SO.UIDNumber,
	SO.AdhaarNumber,
	A.ClassId AS ClassId,
	A.DivisionId AS DivisionId,
	(SELECT Title FROM sSetup.tClassMaster WHERE Id = A.ClassId) AS ClassTitle,
	(SELECT OrderIndex FROM sSetup.tClassMaster WHERE Id = A.ClassId) AS ClassOrderIndex,
	(SELECT Title FROM sSetup.tDivisionMaster WHERE Id = A.DivisionId) AS DivisionTitle,
	(SELECT OrderIndex FROM sSetup.tDivisionMaster WHERE Id = A.DivisionId) AS DivisionOrderIndex,
	--CM.Title AS ClassTitle,
	--DM.Title AS DivisionTitle,
	--CM.OrderIndex AS ClassOrderIndex,
	--DM.OrderIndex AS DivisionOrderIndex
	[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS NameAsPerOrgWise,
	@rBuilder1 AS Builder1,				--add for mantis 27006
	@rBuilder2 AS Builder2,				--add for mantis 27006
	BM.Title AS BatchName       -- add for mantis 0029335
from
	sAttendance.tYearlyRegister YR
	INNER JOIN sStudent.tAcademic A ON A.Id=YR.AcademicId
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId 	
	INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	--INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
	--INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id= A.BatchId -- add for mantis 0029335
where 


	((YR.AcademicId=@rAcademicId) OR (@rAcademicId=0))
	AND(A.BatchId=@rBatchId)
	AND((A.ClassId=@rClassId) OR (@rClassId=0))
	AND((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((SM.StatusId=@rStatus) OR (@rStatus=0))
	AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
	AND((YR.AttendanceTypeId = @rAttendanceTypeId) OR (@rAttendanceTypeId = 0))  -- MantisId : 0029240
	order by A.RollNo 
 
	 END
GO
PRINT N'Altering Procedure [sAssessment].[pMonthlyRegisterGet]...';


GO


ALTER PROCEDURE [sAssessment].[pMonthlyRegisterGet]

	 
	 @rAcedamicId bigint,
	 @rExamId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

SELECT  
	
	 Convert(nvarchar(20),A.Id) AS   AcademicIdText,	
	CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
	 
	A.Id AS AcademicId,
	YR.AvergeAttendance,
	YR.TotalDays,
	YR.PresentDays,
	
	YR.Month1,
	YR.PresentDays1,
	YR.TotalDays1,
	
	YR.Month2,
	YR.PresentDays2,
	YR.TotalDays2,
	
	YR.Month3,
	YR.PresentDays3,
	YR.TotalDays3,
	
	YR.Month4,
	YR.PresentDays4,
	YR.TotalDays4,
	
	YR.Month5,
	YR.PresentDays5,
	YR.TotalDays5,
	
	YR.Month6,
	YR.PresentDays6,
	YR.TotalDays6,
	
	YR.Month7,
	YR.PresentDays7,
	YR.TotalDays7,
	
	YR.Month8,
	YR.PresentDays8,
	YR.TotalDays8,
	
	YR.Month9,
	YR.PresentDays9,
	YR.TotalDays9,
	
	YR.Month10,
	YR.PresentDays10,
	YR.TotalDays10,
	
	YR.Month11,
	YR.PresentDays11,
	YR.TotalDays11,
	
	YR.Month12,
	YR.PresentDays12,
	YR.TotalDays12
	
from
	sAttendance.tYearlyRegister YR
	INNER JOIN sStudent.tAcademic A ON A.Id=YR.AcademicId

where 

	((YR.AcademicId=@rAcedamicId) OR (@rAcedamicId=0))
	AND YR.AttendanceTypeId = 1 -- MantisId : 0029240
	
END
GO
PRINT N'Altering Procedure [sAttendance].[pDeleteAttendance]...';


GO


ALTER PROCEDURE [sAttendance].[pDeleteAttendance]
	 
		@rAttendanceTypeId int=0,	 
		@rClassId int=0,
		@rDivisionId int=0,	
		@rSubjectId int=0,
		@rAcademicId bigint,
		@rBatchId int=0,	 
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0, 
	    @rCode nvarchar(20)='',
	    @rDeleteType nvarchar(20)='',
	    @rFromAttendanceDate Date ='',
	    @rToAttendanceDate Date ='',
	    @rRepeatCount tinyint=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	

IF (@rDeleteType = 'DayRegister')

BEGIN

DELETE sAttendance.tStudentRegister
		FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.tAcademic vSA 
		ON vSA.ID=SR.AcademicId
	WHERE 
		SR.AttendanceTypeId=@rAttendanceTypeId
		AND ((SR.AttendanceDate >= @rFromAttendanceDate))
		AND ((SR.AttendanceDate <= @rToAttendanceDate))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((SR.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND ((SR.RepeatCount=@rRepeatCount) OR (@rRepeatCount=0))
		AND vSA.BatchId=@rBatchId
END

IF(@rDeleteType = 'MonthlyRegister')

BEGIN

DELETE sAttendance.tMonthlyRegister
		FROM sAttendance.tMonthlyRegister MR
		INNER JOIN sStudent.tAcademic vSA 
		ON vSA.Id=MR.AcademicId
	WHERE 
		MR.AttendanceTypeId=@rAttendanceTypeId
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((MR.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND vSA.BatchId=@rBatchId
		
		
		
		DELETE sAttendance.tYearlyRegister
		FROM sAttendance.tYearlyRegister YR
		INNER JOIN sStudent.tAcademic vSA 
		ON vSA.Id=YR.AcademicId
	WHERE 
		 
		  ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))		 
		AND ((YR.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND vSA.BatchId=@rBatchId
		AND YR.AttendanceTypeId = @rAttendanceTypeId -- MantisId : 0029240
END

IF(@rDeleteType = 'StudentSetup')

BEGIN

DELETE sAttendance.tStudentSetup
		FROM sAttendance.tStudentSetup SS
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=SS.AcademicId
	WHERE 
	    (vSA.ClassId=@rClassId) OR (@rClassId=0)
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SS.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND vSA.BatchId=@rBatchId
END

SELECT 1 AS Result

END
GO
PRINT N'Altering Procedure [sAttendance].[pYearlyRegisterUpdate]...';


GO

ALTER PROCEDURE [sAttendance].[pYearlyRegisterUpdate]

     @rOrgId int,
	 @rBatchId int,
	 @rAttendanceTypeId tinyint = 1  -- MantisId : 0029240
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @lQuery AS nvarchar(max)
	
	DELETE YR FROM sAttendance.tYearlyRegister  YR INNER JOIN
	sStudent.tAcademic A ON YR.AcademicId = A.Id
	WHERE A.BatchId = @rBatchId AND YR.AttendanceTypeId = @rAttendanceTypeId -- MantisId : 0029240
 
 	INSERT INTO sAttendance.tYearlyRegister(AcademicId,AttendanceTypeId) 
	SELECT Id, @rAttendanceTypeId FROM sStudent.tAcademic WHERE BatchId = @rBatchId
	
	
		CREATE TABLE #tempClass
	(	Id int IDENTITY,
		ClassId int  
	)
	
	INSERT INTO #tempClass (ClassId) 
	SELECT  ID FROM sSetup.tClassMaster  WHERE OrgId = @rOrgId
	
	
	DECLARE @lClassCount int,@lClassId int
	DECLARE @lClassCounter int 
	SET @lClassCounter = 0
	
	Select @lClassCount = MAX(Id) from #tempClass
	
 	while (@lClassCounter <= @lClassCount)
	BEGIN
	
	SELECT @lClassId = ClassId FROM #tempClass WHERe Id = @lClassCounter
	
	
 	CREATE TABLE #tempMonthlySetup
	(	Id int IDENTITY,
		ForMonth int,
		ForYear int,
		ClassId int
	)
	
	INSERT INTO #tempMonthlySetup (ForMonth,ForYear,ClassId) 
	SELECT MS.ForMonth, MS.ForYear,MS.ClassId FROM 
	sSetup.fMonthYearForBatchGET(@rBatchId) AS MY
	LEFT JOIN sAttendance.tMonthlySetup MS ON MS.BatchId=MY.BatchId AND (MS.ClassId=@lClassId) AND MS.ForMonth = MY.MonthNumber AND MS.ForYear = MY.YearNumber WHERE MY.BatchId=@rBatchId
 
	
	DECLARE @lCount int
	
	DECLARE @lCounter int,@lForMonth int,@lForYear int
	Select @lCount = MAX(Id) from #tempMonthlySetup
	
	 SET @lCounter = 1
	 IF (@lCount > 12) 
	 SET @lCount =12
	while (@lCounter <= @lCount)
	BEGIN
	 
	SELECT @lForMonth = ForMonth ,@lForYear = ForYear FROM #tempMonthlySetup WHERe Id = @lCounter
	
	



SET @lQuery = 'UPDATE YR    
    SET Month' +   convert(nvarchar(15),@lCounter)+  ' = MM.Code,
    TotalDays' +   convert(nvarchar(15),@lCounter)+  ' = MR.TotalCount,
    PresentDays' +   convert(nvarchar(15),@lCounter)+  ' = MR.PresentCount 
    from sAttendance.tYearlyRegister YR
    INNER JOIN sAttendance.tMonthlyRegister MR
    ON YR.AcademicId = MR.AcademicId AND YR.AttendanceTypeId = MR.AttendanceTypeId
    AND MR.ForMonth = '  + convert(nvarchar(15),@lForMonth)  + ' AND MR.ForYear = ' + convert(nvarchar(15),@lForYear)  +
    ' INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
    INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
    AND A.BatchId = ' +  convert(nvarchar(15),@rBatchId)  + ' AND A.ClassId = ' + convert(nvarchar(15),@lClassId) +
	' WHERE YR.AttendanceTypeId = ' +  convert(nvarchar(5),@rAttendanceTypeId)
    

    
print @lQuery
execute(@lQuery)
	
	--IF 	(@lCounter = 1)
	--BEGIN
 
	--UPDATE YR    
 --   SET Month1  = MM.Title,TotalDays1 = MR.TotalCount,PresentDays1 = MR.PresentCount 
 --   from sAttendance.tYearlyRegister YR
 --   INNER JOIN sAttendance.tMonthlyRegister MR
 --   ON YR.AcademicId = MR.AcademicId
 --   AND MR.ForMonth = @lForMonth AND MR.ForYear = @lForYear
 --   INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
 --   INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
 --   AND A.BatchId = @rBatchId AND A.ClassId = @lClassId
    
	--END
	--ELSE IF (@lCounter = 2)
	--BEGIN

	--UPDATE YR    
 --   SET Month2  = MM.Title,TotalDays2 = MR.TotalCount,PresentDays2 = MR.PresentCount 
 --   from sAttendance.tYearlyRegister YR
 --   INNER JOIN sAttendance.tMonthlyRegister MR
 --   ON YR.AcademicId = MR.AcademicId
 --   AND MR.ForMonth = @lForMonth ANd MR.ForYear = @lForYear
 --   INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
 --   INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
 --   AND A.BatchId = @rBatchId AND A.ClassId = @lClassId
    
	--END
 
		SET @lCounter = @lCounter + 1
	END
	DROP TABLE #tempMonthlySetup
	SET @lClassCounter = @lClassCounter + 1
	END 

    UPDATE YR 
    SET TotalDays = (ISNULL(TotalDays1,0) + ISNULL(TotalDays2,0) + ISNULL(TotalDays3,0) + ISNULL(TotalDays4,0) + ISNULL(TotalDays5,0) + ISNULL(TotalDays6,0)
					+ ISNULL(TotalDays7,0) + ISNULL(TotalDays8,0) + ISNULL(TotalDays9,0) + ISNULL(TotalDays10,0) + ISNULL(TotalDays11,0) + ISNULL(TotalDays12,0)),
		PresentDays = ((ISNULL(PresentDays1,0) + ISNULL(PresentDays2,0) + ISNULL(PresentDays3,0) + ISNULL(PresentDays4,0) + ISNULL(PresentDays5,0) + ISNULL(PresentDays6,0)
					+ ISNULL(PresentDays7,0) + ISNULL(PresentDays8,0) + ISNULL(PresentDays9,0) + ISNULL(PresentDays10,0) + ISNULL(PresentDays11,0) + ISNULL(PresentDays12,0)))		
     FROM sAttendance.tYearlyRegister AS YR
    INNER JOIN sStudent.tAcademic A ON YR.AcademicId = A.Id
    WHERE  A.BatchId = @rBatchId 
	AND YR.AttendanceTypeId = @rAttendanceTypeId -- MantisId : 0029240
 
    UPDATE  YR
    
    SET YR.AvergeAttendance = (round(CAST(YR.PresentDays AS float)  / CAST(YR.TotalDays AS float),2)) * 100 
    FROM sAttendance.tYearlyRegister AS YR
    INNER JOIN sStudent.tAcademic A ON YR.AcademicId = A.Id	
    WHERE YR.TotalDays <> 0 AND A.BatchId = @rBatchId 
	AND YR.AttendanceTypeId = @rAttendanceTypeId -- MantisId : 0029240
    	 
	 DROP TABLE #tempClass
 
	
END
GO
PRINT N'Altering Procedure [sAcademic].[pLessonPlanGet]...';


GO


ALTER PROCEDURE [sAcademic].[pLessonPlanGet]

	 @rId bigint=0,
	 @rClassId int=0,
	 @rSubjectId int=0,
	 @rDivisionId int=0,
	 @rIsCompleted bit=0,
	 @rBatchId int=0,
	 @rEmployeeId bigint=0,
	 @rDepartmentid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rCreatedUserId bigint=0,
	 @rStatus int = 0,
	 @rIsWithHeader bit=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	IF(@rStatus = 0)
	BEGIN
	SELECT 
			LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			ISNULL(LP.IsCompleted,0) AS IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			--ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic,
			@rIsWithHeader AS IsWithHeader,
			(CASE WHEN @rIsWithHeader=1 THEN OI.CertificateHeaderA4 ELSE NULL END)AS MarksheetHeaderA4 ,
			ISNULL(LP.[Session] ,'') As [Session] ,
			ISNULL(LP.TrainingMethod,'') As TrainingMethod,
			ISNULL(LP.PeriodCount,0) As PeriodCount ,
			ISNULL(LP.Remark,'') As Remark
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId   
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = CM.OrgId
			--sAcademic.tLessonPlan LP
			--INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
		((LP.BatchId = @rBatchId) OR (@rBatchId = 0))
		 AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))		
		AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		--AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
		--AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		--OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		--)
		--comment above condition because OR is wrong
		AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		AND (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		)
		--comment above condition due to mantisid - 0029580
		--AND ((LP.StartDate = @rFromDate OR ISNULL(@rFromDate,'')='' ))
		--AND ((LP.EndDate = @rToDate OR ISNULL(@rToDate,'')='' ))
		AND (LP.CreatedUserId=@rCreatedUserId OR ISNULL(@rCreatedUserId,'')='')
		AND ISNULL(EM.IsOtherUser,0) = 0
	ORDER BY
		LP.id 
	END
	ELSE
	BEGIN
	SELECT 
			LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			ISNULL(LP.IsCompleted,0) AS IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			--ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic,
			@rIsWithHeader AS IsWithHeader,
			(CASE WHEN @rIsWithHeader=1 THEN OI.CertificateHeaderA4 ELSE NULL END)AS MarksheetHeaderA4 ,
			ISNULL(LP.Session ,'') As [Session],
			ISNULL(LP.TrainingMethod,'') As TrainingMethod,
			ISNULL(LP.PeriodCount,0) As PeriodCount,
			ISNULL(LP.Remark,'') As Remark
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId 
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = CM.OrgId  

			--sAcademic.tLessonPlan LP
			--INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
		((LP.BatchId = @rBatchId) OR (@rBatchId = 0))
		 AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((@rStatus = 2) OR (LP.IsCompleted=@rIsCompleted))
		AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		--AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
	 --   AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		--OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		--)
		--comment above condition because OR is wrong
		AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		AND (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		)
		--comment above condition due to mantisid - 0029580
		--AND ((LP.StartDate = @rFromDate OR ISNULL(@rFromDate,'')='' ))
		--AND ((LP.EndDate = @rToDate OR ISNULL(@rToDate,'')='' ))
		AND (LP.CreatedUserId=@rCreatedUserId OR ISNULL(@rCreatedUserId,'')='')
		AND ISNULL(EM.IsOtherUser,0) = 0
	ORDER BY
		LP.id 
	END
END
GO
PRINT N'Altering Procedure [sAcademic].[pOnlineLearningHistoryAdd]...';


GO
 
ALTER PROCEDURE [sAcademic].[pOnlineLearningHistoryAdd]
	@rFromDate DATE,
	@rToDate DATE,
	@rCreatedUserId Bigint,
	@rBatchId Bigint,
	@rStatus NVARCHAR(30)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	--insert into [sAcademic].[tOnlineLearningAttendanceLog]

	INSERT INTO [sAcademic].[tOnlineLearningAttendanceLogHistory]
	SELECT OLAL.OnlineLearningId,OLAL.AcademicId,OLAL.ActivityId,OLAL.CreatedDateTime
	FROM sAcademic.tOnlineLearningAttendanceLog OLAL
	INNER JOIN sAcademic.tOnlineLearning OL ON OLAL.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	DELETE OLAL FROM sAcademic.tOnlineLearningAttendanceLog OLAL
	INNER JOIN sAcademic.tOnlineLearning OL ON OLAL.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	--insert into [sAcademic].[tOnlineLearningAttendance]

	INSERT INTO [sAcademic].[tOnlineLearningAttendanceHistory]
	SELECT OLAL.* 
	FROM sAcademic.tOnlineLearningAttendance OLAL
	INNER JOIN sAcademic.tOnlineLearning OL ON OLAL.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	DELETE OLAL FROM sAcademic.tOnlineLearningAttendance OLAL
	INNER JOIN sAcademic.tOnlineLearning OL ON OLAL.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	--insert into [sAcademic].[tOnlineLearningRecording]

	INSERT INTO [sAcademic].[tOnlineLearningRecordingHistory]
	SELECT OLR.OnlineLearningId,OLR.RecordingId,OLR.RecordingStart,OLR.RecordingEnd,
	OLR.FileType,OLR.FileExtension,OLR.FileSize,OLR.PlayURL,OLR.DownloadURL,OLR.Status,OLR.RecordingType,OLR.CreatedDateTime 
	FROM sAcademic.tOnlineLearningRecording OLR
	INNER JOIN sAcademic.tOnlineLearning OL ON OLR.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	DELETE OLR FROM sAcademic.tOnlineLearningRecording OLR
	INNER JOIN sAcademic.tOnlineLearning OL ON OLR.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	--insert into [sAcademic].[tOnlineLearningAssignmentSubmitHistory]

	INSERT INTO [sAcademic].[tOnlineLearningAssignmentSubmitHistory]
	SELECT OLAS.OnlineLearningId,OLAS.AcademicId,OLAS.AssignmentPath,OLAS.DeletedUser,OLAS.DeletedDateTime 
	FROM sAcademic.tOnlineLearningAssignmentSubmit OLAS
	INNER JOIN sAcademic.tOnlineLearning OL ON OLAS.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 


	DELETE OLAS FROM sAcademic.tOnlineLearningAssignmentSubmit OLAS
	INNER JOIN sAcademic.tOnlineLearning OL ON OLAS.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	--insert into [sAcademic].[tOnlineLearningAssignmentHistory]

	INSERT INTO [sAcademic].[tOnlineLearningAssignmentHistory]
	SELECT OlA.AutoID,OLA.OnlineLearningId,OLA.AssignmentPath 
	FROM sAcademic.tOnlineLearningAssignment OLA
	INNER JOIN sAcademic.tOnlineLearning OL ON OLA.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	DELETE OLA FROM sAcademic.tOnlineLearningAssignment OLA
	INNER JOIN sAcademic.tOnlineLearning OL ON OLA.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	--insert into [sAcademic].[tOnlineLearningReferenceHistory]

	INSERT INTO [sAcademic].[tOnlineLearningReferenceHistory]
	SELECT OLR.OnlineLearningId,OLR.ReferencePath 
	FROM sAcademic.tOnlineLearningReference OLR
	INNER JOIN sAcademic.tOnlineLearning OL ON OLR.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	DELETE OLR FROM sAcademic.tOnlineLearningReference OLR
	INNER JOIN sAcademic.tOnlineLearning OL ON OLR.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate)  

	--insert into [sAcademic].[tOnlineLearningResourceHistory]

	INSERT INTO [sAcademic].[tOnlineLearningResourceHistory]
	SELECT OLR.OnlineLearningId,OLR.ResourceTypeId,OLR.ResourcePath
	FROM sAcademic.tOnlineLearningResource OLR
	INNER JOIN sAcademic.tOnlineLearning OL ON OLR.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	DELETE OLR FROM sAcademic.tOnlineLearningResource OLR
	INNER JOIN sAcademic.tOnlineLearning OL ON OLR.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	--insert into [sAcademic].[tOnlineLearningViewHistory]

	INSERT INTO [sAcademic].[tOnlineLearningViewHistory]
	SELECT OLV.OnlineLearningId,OLV.AcademicId,OLV.IsViewReference,OLV.IsViewAssignment,OLV.IsViewResource,OLV.ViewByUserId,OLV.LastViewByDateTime,OLV.AssignmentTeacherRemark
	FROM sAcademic.tOnlineLearningView OLV
	INNER JOIN sAcademic.tOnlineLearning OL ON OLV.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	DELETE OLV FROM sAcademic.tOnlineLearningView OLV
	INNER JOIN sAcademic.tOnlineLearning OL ON OLV.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	--insert into [sAcademic].[tOnlineLearningScopeHistory]

	INSERT INTO [sAcademic].[tOnlineLearningScopeHistory]
	SELECT OLS.* 
	FROM sAcademic.tOnlineLearningScope OLS
	INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	DELETE OLS FROM sAcademic.tOnlineLearningScope OLS
	INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	--insert into [sAcademic].[tOnlineLearningHistory]

	INSERT INTO [sAcademic].[tOnlineLearningHistory]
	SELECT * 
	FROM sAcademic.tOnlineLearning OL
	WHERE convert(date,OL.CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,OL.CreatedDateTime) <= convert(date,@rToDate) 

	DELETE FROM sAcademic.tOnlineLearning 
	WHERE convert(date,CreatedDateTime) >= convert(date,@rFromDate) 
	AND convert(date,CreatedDateTime) <= convert(date,@rToDate) 
	 
	INSERT INTO 
	   sAcademic.tOnlineLearningHistoryLog
	VALUES
	(
	  @rBatchId,
	  @rFromDate,
	  @rToDate,
	  @rCreatedUserId,
	  sCommon.fGetDate(),
	  @rStatus
	)

	SELECT 1 AS RESULT
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricFirstInTimeGet]...';


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

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			--add for 29368 mantis--> add @lDateTimeNow, in @lCloudTransactionDataId add CreatedDateTime filter
			declare @lDateTimeNow datetime=[sCommon].[fGetDate]()

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

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

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

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

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


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


GO
ALTER PROCEDURE [sAlert].[pFeedbackGet]
	  
        @rFeedbackId bigint=0,
        @rOrgId int,
	 	@rTemplate nvarchar(max),
		@rSubject nvarchar(100)=''
		
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 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 FirstName +' ' + MiddleName+' ' + LastName
			   
			From sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 END) AS Name,
		 
		 (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			 Code
			From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 Code
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 END) AS Code,

		 (CASE AssignToSourceTypeId WHEN  95
		 THEN
			(Select 
			 EC.MobileNumber
			From sHrm.tEmployeeMaster EM
			Inner Join sHrm.vEmployeeCommunication EC ON EC.Id=EM.Id
			Where  EM.Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(EM.IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 AC.ParentContactNo 
			From sStudent.tAcademic A
			INNER JOIN sStudent.vStudentCommunication AC  ON A.Id=AC.AcademicId 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 END) AS MobileNo,

		 (CASE AssignToSourceTypeId WHEN  95
		 THEN
			(Select 
			 EC.CompanyEmail
			From sHrm.tEmployeeMaster EM
			Inner Join sHrm.vEmployeeCommunication EC ON EC.Id=EM.Id
			Where  EM.Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(EM.IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 AC.ParentEmail 
			From sStudent.tAcademic A
			INNER JOIN sStudent.vStudentCommunication AC  ON A.Id=AC.AcademicId 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 END) AS EmailId,

		 (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			EC.WhatsAppContactNo
			From sHrm.tEmployeeMaster EM
			Inner Join sHrm.vEmployeeCommunication EC ON EC.Id=EM.Id
			Where  EM.Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(EM.IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			  AC.WhatsAppContactNo
			From sStudent.tAcademic A 
			INNER JOIN sStudent.vStudentCommunication AC  ON A.Id=AC.AcademicId 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 END) AS WhatsAppContactNo,

		replace(@rTemplate,'[Title]',F.Title) AS MsgText,
		@rSubject AS Subject,

		  (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			 Id
			From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 A.Id
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 END) AS SourceId,
		Isnull(AssignToSourceTypeId,0) AS ReceiverSourceTypeId,
		Isnull(AssignToSourceId,0)AS ReceiverSourceId,
		FeedbackId AS FeedbackId,
		ISNULL(OM.OrgGroupId,0) AS OrgGroupId,
		ISNULL(OM.Id,0) AS OrgId,
		Isnull(AssignToSourceTypeId,0) AS SourceTypeId
		
	from sCommunication.tFeedbackAssign FB
	INNER JOIN sCommunication.tFeedback F ON F.Id=FB.FeedbackId
	INNER JOIN  sSetup.tOrgGroupBatchMaster OGM ON OGM.Id=F.OrgGroupBatchId
	--INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id =  OGM.OrgGroupId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.OrgGroupId
	Where  ((FB.FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))
	--AND (OM.Id=@rOrgId OR @rOrgId=0)  -- Commented for Mantis 0029364 By Foram
	 
END
GO
PRINT N'Altering Procedure [sAlert].[pResultWithDetailsGet]...';


GO
 

ALTER PROCEDURE [sAlert].[pResultWithDetailsGet]
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rExamId int,
	 	 @rSubjectId int=0,
		 @rIsSubjectInNewLine bit = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rIsSubjectInNewLine = 0)
	BEGIN
		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,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ExamName]',ES.Title),
			'[SubjectMark]', CHAR(13) + [sAlert].[fResultGet](R.Id,@rSubjectId,1)),
			'[SubjectMarkWithMax]',[sAlert].[fResultWithMaxGet](R.Id,@rSubjectId)),
			'[TotalMarks]',CONVERT(int,TotalMarks)),
			'[ObtainMarks]',CONVERT(int,TotalObtain)),
			'[ResultStatus]',R.ResultStatus),
			'[ResultGrade]',R.ResultGrade),
			'[ResultGradePoint]',R.ResultGradePoint),
			'[RankNumber]',R.RankNumber),
			'[Percentage]',R.Percentage),
			'[SubjectGrade]',[sAlert].[fResultGet](R.Id,@rSubjectId,2)),
			'[Percentile]',R.Percentile)
			
			 AS Template,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 ES.Title AS ExamName,
			 CONVERT(int,TotalMarks) AS TotalMarks,
			 CONVERT(int,TotalObtain) AS ObtainMarks,
			 R.ResultStatus AS ResultStatus,
			 R.ResultGrade AS ResultGrade,
			 R.ResultGradePoint AS ResultGradePoint,
			 R.RankNumber AS RankNumber,
			 R.Percentage AS Percentage,
			 R.Percentile AS Percentile,
			 [sAlert].[fResultGet](R.Id,@rSubjectId,2) AS SubjectGrade,
			 [sAlert].[fResultWithMaxGet](R.Id,@rSubjectId) AS SubjectMarkWithMax,
			 SC.WhatsAppContactNo
		
	From 
	sStudent.vStudentCommunication SC
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SC.AcademicId AND (R.ExamId=@rExamId OR @rExamId=0)
	INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = E.ExamSubGroupId
	 
	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 SC.IsBlockAllAlert=0
	ORDER BY SC.DivisionOrderIndex,SC.Rollno
	END
	ELSE
	BEGIN
		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,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ExamName]',ES.Title),
			'[SubjectMark]',[sAlert].[fResultGetWithLineBreak](R.Id,@rSubjectId,1)),
			'[SubjectMarkWithMax]',[sAlert].[fResultWithMaxGetWithLineBreak](R.Id,@rSubjectId)),
			'[TotalMarks]',CONVERT(int,TotalMarks)),
			'[ObtainMarks]',CONVERT(int,TotalObtain)),
			'[ResultStatus]',R.ResultStatus),
			'[ResultGrade]',R.ResultGrade),
			'[ResultGradePoint]',R.ResultGradePoint),
			'[RankNumber]',R.RankNumber),
			'[Percentage]',R.Percentage),
			'[SubjectGrade]',[sAlert].[fResultGetWithLineBreak](R.Id,@rSubjectId,2)),
			'[Percentile]',R.Percentile)
			
			 AS Template,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 ES.Title AS ExamName,
			 CONVERT(int,TotalMarks) AS TotalMarks,
			 CONVERT(int,TotalObtain) AS ObtainMarks,
			 R.ResultStatus AS ResultStatus,
			 R.ResultGrade AS ResultGrade,
			 R.ResultGradePoint AS ResultGradePoint,
			 R.RankNumber AS RankNumber,
			 R.Percentage AS Percentage,
			 R.Percentile AS Percentile,
			 [sAlert].[fResultGet](R.Id,@rSubjectId,2) AS SubjectGrade,
			 [sAlert].[fResultWithMaxGet](R.Id,@rSubjectId) AS SubjectMarkWithMax,
			 SC.WhatsAppContactNo
		
	From 
	sStudent.vStudentCommunication SC
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SC.AcademicId AND (R.ExamId=@rExamId OR @rExamId=0)
	INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = E.ExamSubGroupId
	 
	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 SC.IsBlockAllAlert=0
	ORDER BY SC.DivisionOrderIndex,SC.Rollno
	END
END
GO
PRINT N'Altering Procedure [sAlert].[pVisitorGatePassGet]...';


GO
ALTER PROCEDURE [sAlert].[pVisitorGatePassGet]
	
		 @rVisitorLogId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
		 @rSubject nvarchar(100)='',
		 @rIsOutEntry bit = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rIsOutEntry=0)
	BEGIN
		SELECT 
			VL.Id,
			VL.VisitorName,
			EC.MobileNumber AS MobileNo,
			VL.VisitorContactNumber AS ContactNumber,
			EC.CompanyEmail AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[VisitorName]',VL.VisitorName),
			'[NoOfVisitors]',VL.NoOfVisitor),
			'[PurposeOfVisit]',VL.PurposeOfVisit),
			'[SchoolName]',OM.DisplayTitle),
			'[GatepassNumber]',VL.Id),
			'[VisitDate]',VL.VisitDate) AS MsgText,
			@rSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EM.Id AS ReceiverSourceId,
			EM.Id AS SourceId,
			95 AS SourceTypeId,
			OM.OrgGroupId,
			VL.OrgId,
			VL.NoOfVisitor AS NoOfVisitors,
			VL.PurposeOfVisit AS PurposeOfVisit,
			ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sFrontOffice.tVisitorLog VL
			INNER JOIN [sHrm].[tEmployeeMaster] EM ON VL.WhomToMeet=EM.Id
			INNER JOIN [sHrm].[tEmployeeCommunications] EC ON EM.Id=EC.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON VL.OrgId = OM.Id	
		WHERE
			((VL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND VL.Id = @rVisitorLogId
	END
	ELSE
	BEGIN
		SELECT 
			VL.Id,
			VL.VisitorName,
			VL.VisitorContactNumber AS MobileNo,
			'' AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[VisitorName]',VL.VisitorName),
			'[NoOfVisitors]',VL.NoOfVisitor),
			'[PurposeOfVisit]',VL.PurposeOfVisit),
			'[SchoolName]',OM.DisplayTitle),
			'[GatepassNumber]',VL.Id),
			'[VisitDate]',VL.VisitDate) AS MsgText,
			@rSubject AS Subject,
			0 AS ReceiverSourceTypeId,
			0 AS ReceiverSourceId,
			0 AS SourceId,
			0 AS SourceTypeId,
			OM.OrgGroupId,
			VL.OrgId,
			VL.NoOfVisitor AS NoOfVisitors,
			VL.PurposeOfVisit AS PurposeOfVisit,
			ISNULL(VL.VisitorContactNumber,'') AS WhatsAppContactNo
		FROM 
			sFrontOffice.tVisitorLog VL
			--To Send Alert on Visitor Contact No
			--LEFT JOIN [sHrm].[tEmployeeMaster] EM ON VL.WhomToMeet=EM.Id
			--LEFT JOIN [sHrm].[tEmployeeCommunications] EC ON EM.Id=EC.EmployeeId
			LEFT JOIN sSetup.tOrganizationMaster OM ON VL.OrgId = OM.Id	
		WHERE
			((VL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND VL.Id = @rVisitorLogId
	END
END
GO
PRINT N'Altering Procedure [sAssessment].[pMarkEntryGet]...';


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

BEGIN 		

if(@rIsWithPhoto=1)
BEGIN
SELECT 
	
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,ISNULL(RD.Id,0) AS ResultDetailId
	,ISNULL(R.Id,0) AS ResultId  
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,CASE WHEN ISNULL(EM.IsMarksInDecimal,0) = 1 THEN ISNULL(RD.Obtain,0) ELSE ROUND(ISNULL(RD.Obtain,0),0) END  AS Obtain
	--,ISNULL(RD.Obtain,0) AS Obtain
	,ISNULL(RD.IsPresent,'true') as IsPresent
	,ED.Id AS ExamDetailId
	,ED.Maximum AS MaximumMark
	,ISNULL(EM.IsMarksInDecimal,0) AS IsMarkInDecimal
	,ISNULL(EM.IsNegativeMarks,0) AS IsNegativeMarks,
	ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
	ISNULL(ED.ExamTopic,'') as ExamTopic,
	0 AS PresentTotal,
	0 AS TotalCount,
	CASE WHEN RD.IsPresent = 0 THEN ISNULL(RD.AbsentRemark,'') ELSE ''  END AS AbsentRemark

from sStudent.vStudentAcademic SA 
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
	LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
	LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicId and o.ClassSubjectId=V.ClassSubjectId

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

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

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


GO

ALTER PROCEDURE [sAssessment].[pRptResultListFloatingCombineExam]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rIsShowWithDetail bit =0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0
	 --@rFromPercentage decimal(5,2)=0,
	 --@rToPercentage decimal(5,2)=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 --Select * from dbo.Float
 --Select
 --           ''  AS AcademicIdText,
	--		'' AS ExamIdText,
	--		'' AS IsDisplayMonthlyAttendanceText,
	--		'' AS Exam,
	--		'' AS Builder1,
	--		'' Code,
	--		'' AS Name,
	--		0 RollNo,
	--		CONVERT(BigInt, 0) AcademicId,			
	--		'' ResultStatus,
	--		'' AS Class,
	--		'' AS Division,
	--		CONVERT(Decimal, 0) TotalMarks,
	--		CONVERT(Decimal, 0) TotalObtain,
	--		CONVERT(Decimal, 0) Percentage,
	--		0 RankNumber,
	--		'' ResultGrade,
	--		CONVERT(Decimal, 0) Percentile,			
	--		CONVERT(BigInt, 0) AS ResultDetailId,		
	--		CONVERT(Bit, 0) IsDisplayInMarksheet,
	--		CONVERT(Bit, 0) IsShowSubjectGrade,
	--		CONVERT(Bit, 0) IsIncludeInTotal,
	--		CONVERT(Decimal, 0) AS SubjectObtain,
	--		CONVERT(Decimal, 0) AS SubjectMinimum,
	--		CONVERT(Decimal, 0) AS SubjectMaximum,			
	--		'' AS SubjectCode,
	--		'' AS SubjectName,
	--		0 AS SubjectOrderIndex,
	--		CONVERT(BigInt, 0) AS ResultId,
	--		0 AS SubjectId,			 	
	--		CONVERT(Bit, 0) IsMarksInDecimal,
			
	--		'' AS Remark1,
	--		'' AS Remark2,
	--		'' AS Remark3,
	--		'' DisplayTitle,
	--		CONVERT(Bit, 0) IsRankNo, 
	--		CONVERT(Bit, 0) IsGrade,
	--		CONVERT(Bit, 0) IsPercentile,
	--		CONVERT(Bit, 0) IsPercentage,
	--		CONVERT(Bit, 0) IsSubjectPercentile,
	--		CONVERT(Bit, 0) IsProcessResult,
			 
	--		CONVERT(Bit, 0) IsNegativeMarks,
	--		CONVERT(Bit, 0) IsIncludeCoScholastic,
	--		CONVERT(Bit, 0) IsOnPrePrinted,
	--		CONVERT(Bit, 0) IsDisplayPhoto,
	--		CONVERT(Bit, 0) IsDisplayBirthDate,
	--		CONVERT(Bit, 0) IsLockForEdit,
	--		CONVERT(Bit, 0) IsDisplaySchoolName,			
	--		CONVERT(Bit, 0) IsDisplayAttendance,
	--		CONVERT(Bit, 0) IsDisplayHeightWeight,
	--		CONVERT(Bit, 0) IsResultStatus,
	--		'' AS FooterAdjustmentText,
	--		'' AS DetailAdjustmentText,
	--		0 FooterAdjustment,
	--		0 DetailAdjustment,
		 		 
	--		0 TermScopeId,
		 
	--		CONVERT(Bit, 0) IsPresent,
	--		'' AS GradeString,
	--		0 IsDisplayGradeString,
	--		CONVERT(Decimal, 0) HighestDivisionMark,
	--		 ''  AS HighestDivisionGrade,			
	--		'' SmallAddress1,
	--		CONVERT(Bit, 0) IsDisplayParentName,
			 
	--		CONVERT(Bit, 0) AS IsShowSubjectMark,
			
	--		CONVERT(Bit, 0) IsDisplayTeacherSign,
	--		CONVERT(Bit, 0) IsDisplayPrincipalSign,
		 
	--		CONVERT(Bit, 0) AS IsDisplayMonthlyAttendance,
			 
	--		CONVERT(Bit, 0) AS IsImageHeader,
			 
	--		0 SubExamId,
	--		0 ExamOrderIndex,
	--		0 AnnualExamId ,
	--		'' DecimalFormat,
	--		0 TermExamId,
	--		'' AS ExamNAme, 			 
	--		'' AS AnnualSubjectGrade,
	--		CONVERT(Decimal, 0) As AnnualSubjectObtain,
	--		'' AS TermSubjectGrade,
	--		CONVERT(Decimal, 0) As TermSubjectObtain ,
	--		'' AS SubjectGrade,
	--		'' AS Remark,
	--		'' AS FatherName,
	--		'' AS	MotherName,
	--		CONVERT(Decimal, 0) AS	TotalDays,
	--		CONVERT(Decimal, 0) AS PresentDays,
	--		CONVERT(Decimal, 0) AS TotalObtain,
	--		CONVERT(Decimal, 0) TermMaximum,
	--		CONVERT(Decimal, 0) AS AnnualMaximum,
	--		'' AS Gender,
	--		0 AS ClassSubjectId,
	--		CONVERT(bit,0) AS IsAbsentRemark
	--		'' AS AbsentRemark
	

 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int , @lIsMarksInDecimal bit , @lDecimalFormat nvarchar(10)
 
SELECT @GradeSetId = GradesetId,@lIsMarksInDecimal = IsMarksInDecimal, @lDecimalFormat = DecimalFormat  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  

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

CREATE TABLE #TempExam
(
	SubExamId int, 
	ExamOrderIndex int,
	TermExamId int,
	AnnualExamId int, 
	Exam nvarchar(50) 
)


INSERT INTO #TempExam
(
	 --SubExamId,
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam 
	
)
 
SELECT EC.ExamOrder,
EM.Id AS TermExamId,
@rExamId AS AnnualExamId,
ESGM.Code AS Exam
  FROM [sAssessment].[tExamMaster] EM 
		INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId =@rExamId  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId
	
	--Select * from #TempExam
	
 --Select * from #TempExam
		Declare @lAnnualExamMaximum int,@lExamId int
		Select @lExamId= AnnualExamId FROM #TempExam 

		Select @lAnnualExamMaximum=Maximum from sAssessment.tExamDetail Where ExamId=@lExamId
	
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			 @rBuilder1 AS Builder1,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			(Select R1.TotalObtain from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS TotalMarks,
			--R.TotalMarks,
			(Select R1.Percentage from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS Percentage,
			R.TotalObtain,
			R.RankNumber,
			(Select R1.ResultGrade from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS ResultGrade,
			--R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			@lIsMarksInDecimal AS IsMarksInDecimal,
			
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			 
			EM.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.TermScopeId,
		 
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
		 
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			 
			EC.SubExamId,
			EC.ExamOrderIndex,
			EC.AnnualExamId ,
			@lDecimalFormat AS DecimalFormat,
			EC.TermExamId,
			EC.Exam AS ExamNAme, 	
					 
			ARD.SubjectGrade AS AnnualSubjectGrade,
			--(Select RD1.SubjectGrade from 
			--sAssessment.tResultDetail RD1
			--INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			--Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			--AND R1.AcademicId=R.AcademicId
			--)AS AnnualSubjectGrade,
			--(Select RD1.Obtain from 
			--sAssessment.tResultDetail RD1
			--INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			--Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			--AND R1.AcademicId=R.AcademicId
			--)AS AnnualSubjectObtain,
			ARD.Obtain As AnnualSubjectObtain,
			--(Select RD1.SubjectGrade from 
			--sAssessment.tResultDetail RD1
			--INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			--Where ED1.ExamId=EC.TermExamId AND ED1.ClassSubjectId=CS.Id 
			--AND R1.AcademicId=R.AcademicId
			--)AS TermSubjectGrade,
			TRD.SubjectGrade AS TermSubjectGrade,
			--(Select RD1.Obtain from 
			--sAssessment.tResultDetail RD1
			--INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			--Where ED1.ExamId=EC.TermExamId AND ED1.ClassSubjectId=CS.Id 
			--AND R1.AcademicId=R.AcademicId
			--)AS TermSubjectObtain,
			TRD.Obtain AS TermSubjectObtain,
			EC.TermExamId,
			RD.Id,
			RD.SubjectGrade AS SubjectGrade,
			ISNULL(ARD.Remark,'')  AS Remark,
			SF.FatherName,
			SF.MotherName,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			--R.TotalMarks AS TotalMark,
			R.TotalObtain,
			(Select Exd.Maximum from sAssessment.tExamDetail Exd Where 
			Exd.ExamId=EC.TermExamId AND CS.Id=Exd.ClassSubjectId
			)AS TermMaximum,
			(Select Exd.Maximum from sAssessment.tExamDetail Exd Where 
			Exd.ExamId=EC.AnnualExamId AND CS.Id=Exd.ClassSubjectId
			)AS AnnualMaximum,
			(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END)AS Gender,
			CS.Id,
			--(Select R.TotalMarks From sAssessment.tResult)
			--@lAnnualExamMaximum AS AnnualMaximum, ROW_NUMBER() OVER (
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			RD.AbsentRemark
						
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.TermExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			INNER JOIN sAssessment.tResult AR ON AR.AcademicId = A.Id AND AR.ExamId = EC.AnnualExamId 
			INNER JOIN sAssessment.tResultDetail ARD ON AR.Id = ARD.ResultId 
			INNER JOIN sAssessment.tExamDetail AED ON ARD.EXamDetailId = AED.Id 
			INNER JOIN sSetup.tClassSubject ACS ON AED.ClassSubjectId = ACS.Id AND ACS.Id= CS.Id
			--AND ACS.SubjectId = @rSubjectId  
			INNER JOIN sAssessment.tResult TR ON TR.AcademicId = A.Id AND TR.ExamId = EC.TermExamId 
			INNER JOIN sAssessment.tResultDetail TRD ON TR.Id = TRD.ResultId 
			INNER JOIN sAssessment.tExamDetail TED ON TRD.EXamDetailId = TED.Id 
			INNER JOIN sSetup.tClassSubject TCS ON TED.ClassSubjectId = TCS.Id AND TCS.Id= CS.Id
			--AND TCS.SubjectId = @rSubjectId 
			
			
			LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.OrgGroupBatchId)) 
		    LEFT JOIN
			(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT ON RT.SourceId = StuM.Id 
		
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND  SR.ExamId=EC.AnnualExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
			
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		--AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		--AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))Total Marks
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    ) 
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		--order by A.RollNo,CS.OrderIndex 
		
	 drop table #TempExam
	 
END
GO
PRINT N'Altering Procedure [sAttendance].[pMonthlyRegisterStudentviewGet]...';


GO

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

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

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

		SET @YearNumber =Year(GETDATE())



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

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


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

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

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

		ORDER BY AcademicId,AttendanceDate -- Added AttendanceDate in order by for mantis id : 29551
		FOR XML PATH('')),2,200000) AS CSV
)
END


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


	Select 
	@lAttedanceGrid = @lAttedanceGrid + '<tr>
	<td align="left" scope="col">' + Isnull(MY.MonthTitle,'')  + '</td>
	<td align="left" scope="col">' +convert(varchar,isnull( MY.YearNumber,0))+ '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AttendanceCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.PresentCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AbsentCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AveragePresence,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar(max),isnull(MR.AbsentDays,0),103) + '</td>  
	</tr>'
	--Change datatype to varchar(max) for AbsentDays for mantis 29551
		From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND MR.AttendanceTypeId=@rAttendanceTypeId
		AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
	WHERE
		SN.AcademicId=@rAcademicId	
	ORDER BY MY.YearNumber,MY.MonthNumber;


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

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

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


GO

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


GO
ALTER PROCEDURE [sCommunication].[pBehaviourGet]
		
		@rId bigint,
		@rBehaviourTypeId int,
		@rOrgGroupBatchId int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rFromDate date='',
		@rToDate date='',
		@rCreatedUserId bigint=0,
		@rBatchId int,
		@rOrgId int = 0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
	B.Id AS BehaviourId,
	B.BehaviourDate,
	B.Title,
	BTM.Title AS BehaviourType,
	SA.Name,
	SA.ClassName+'-'+SA.DivisionName AS ClassDiv,
	SA.Code,
	B.Remark,
	B.BehaviourTypeId,
	B.AcademicId,
	U.DisplayTitle AS UserName,
	SA.OrgId,
	SA.BatchId
  FROM 
        sCommunication.tBehaviour B
        INNER JOIN sCommunication.tBehaviourTypeMaster BTM ON B.BehaviourTypeId=BTM.Id
        INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=B.AcademicId
        INNER JOIN sSecurity.tUser U ON U.Id = B.CreatedUserId
         --INNER JOIN sStudent.tStudentMaster SM ON SM.Id=B.AcademicId
  WHERE 
	((B.Id=@rId) OR (ISNULL(@rId,0)=0))
    AND ((B.BehaviourTypeId= @rBehaviourTypeId) OR (ISNULL(@rBehaviourTypeId,0) = 0)) 
    --AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId))
    AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((B.Title=@rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((B.BehaviourDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND((B.BehaviourDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((B.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
END
GO
PRINT N'Altering Procedure [sCommunication].[pDailyThoughtAssignSearchGet]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rSourceTypeId = 2003)
	BEGIN
		IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @rDay AND Month = @rMonth AND SourceTypeId = 2005 AND SourceId = @rDivisionId)
		BEGIN
			SELECT
				DTA.DailyThoughtId AS Id,
				STUFF ((SELECT ','+ CAST(Number AS nvarchar(20))
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Number,
				STUFF ((SELECT ', '+ Title
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Title,
				STUFF ((SELECT ', '+ Remark
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Remark 
			FROM 
				sCommunication.tDailyThoughtAssign DTA 
			WHERE DTA.OrgId = @rOrgId 
				AND DTA.Day = @rDay AND DTA.Month = @rMonth 
				AND DTA.SourceTypeId = 2005 
				AND DTA.SourceId = @rDivisionId
			ORDER BY DTA.AutoId DESC
		END

		ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @rDay AND Month = @rMonth AND SourceTypeId = 2016 AND SourceId = @rClassId)
		BEGIN
			SELECT
				DTA.DailyThoughtId AS Id,
				STUFF ((SELECT ','+ CAST(Number AS nvarchar(20))
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Number,
				STUFF ((SELECT ', '+ Title
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Title,
				STUFF ((SELECT ', '+ Remark
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Remark 
			FROM 
				sCommunication.tDailyThoughtAssign DTA 
			WHERE DTA.OrgId = @rOrgId 
				AND DTA.Day = @rDay AND DTA.Month = @rMonth 
				AND DTA.SourceTypeId = 2016 
				AND DTA.SourceId = @rClassId
			ORDER BY DTA.AutoId DESC
		END
		ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @rDay AND Month = @rMonth AND SourceTypeId = 2021 AND SourceId = @rOrgId)
		BEGIN
			SELECT
				DTA.DailyThoughtId AS Id,
				STUFF ((SELECT ','+ CAST(Number AS nvarchar(20))
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Number,
				STUFF ((SELECT ', '+ Title
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Title,
				STUFF ((SELECT ', '+ Remark
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Remark 
			FROM 
				sCommunication.tDailyThoughtAssign DTA 
			WHERE DTA.OrgId = @rOrgId 
				AND DTA.Day = @rDay AND DTA.Month = @rMonth 
				AND DTA.SourceTypeId = 2021 
				AND DTA.SourceId = @rOrgId
			ORDER BY DTA.AutoId DESC
		END
	END

	IF(@rSourceTypeId = 95)
	BEGIN
		IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @rDay AND Month = @rMonth AND SourceTypeId = 2017 AND SourceId = @rDepartmentId)
		BEGIN
			SELECT
				DTA.DailyThoughtId AS Id,
				STUFF ((SELECT ','+ CAST(Number AS nvarchar(20))
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Number,
				STUFF ((SELECT ', '+ Title
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Title,
				STUFF ((SELECT ', '+ Remark
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Remark 
			FROM 
				sCommunication.tDailyThoughtAssign DTA 
			WHERE DTA.OrgId = @rOrgId 
				AND DTA.Day = @rDay AND DTA.Month = @rMonth 
				AND DTA.SourceTypeId = 2017 
				AND DTA.SourceId = @rDepartmentId
			ORDER BY DTA.AutoId DESC
		END
		ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @rDay AND Month = @rMonth AND SourceTypeId = 2021 AND SourceId = @rOrgId)
		BEGIN
			SELECT
				DTA.DailyThoughtId AS Id,
				STUFF ((SELECT ','+ CAST(Number AS nvarchar(20))
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Number,
				STUFF ((SELECT ', '+ Title
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Title,
				STUFF ((SELECT ', '+ Remark
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Remark 
			FROM 
				sCommunication.tDailyThoughtAssign DTA 
			WHERE DTA.OrgId = @rOrgId 
				AND DTA.Day = @rDay AND DTA.Month = @rMonth 
				AND DTA.SourceTypeId = 2021 
				AND DTA.SourceId = @rOrgId
			ORDER BY DTA.AutoId DESC
		END
	END
	
END
GO
PRINT N'Altering Procedure [sCommunication].[pDailyThoughtGet]...';


GO
ALTER PROCEDURE [sCommunication].[pDailyThoughtGet]

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

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

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

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

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

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

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

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

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

					SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND (SourceTypeId = 2021 AND SourceId = @lOrgId)
			END
	END
	
	IF(@rSourceTypeId = 95)
	BEGIN

		DECLARE @lDepartmentId int
		SELECT @lDepartmentId = OrganizationDepartmentId FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rSourceId 

		-- Added IF block for Department wise assigned data to employee for Mantis: 0029003 by Foram
		IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2017 AND SourceId = @lDepartmentId)
		BEGIN --Check If DailyThought Assign to particular day Departmentwise
			SELECT 
				DTM.Id,
				DTM.Number,
				DTM.Title,
				DTM.Remark,
				DTS.Title As [Subject]
			FROM
				sCommunication.tDailyThoughtAssign DTA
				INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
				INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
			WHERE
				DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND SourceTypeId = 2017 AND SourceId = @lDepartmentId

			SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2017 AND SourceId = @lDepartmentId
		END

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

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

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


			END
		--Added for mantis 0029003: 3rd point by Foram (Reason: If Daily Thought Master is not there then no need it in temp table also)
		--ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtTemp WHERE CONVERT(NVARCHAR,CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) AND OrgGroupId = @lOrgGroupId)
		--BEGIN --If DailyThought loaded in temp table for particular day 
		--	SELECT 
		--		DTM.Id,
		--		DTM.Number,
		--		DTM.Title,
		--		DTM.Remark,
		--		DTS.Title As [Subject]
		--	FROM
		--		sCommunication.tDailyThoughtTemp DTM 
		--		INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
		--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = DTM.OrgGroupId
		--		INNER JOIN sCommunication.tDailyThoughtMaster DM ON DM.Id = DTM.Id   -- Added Join for mantis 0029003: 3rd point by Foram
		--	WHERE
		--		OM.Id = @rOrgId

		--	-- Added for mantis 0029003: 3rd point by Foram (Reason: If Daily Thought Master is not there then no need it in temp table also)
		--	DELETE DTM 
		--	FROM
		--		sCommunication.tDailyThoughtTemp DTM 
		--		INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
		--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = DTM.OrgGroupId
		--		LEFT JOIN sCommunication.tDailyThoughtMaster DM ON DM.Id = DTM.Id   -- Added Join for mantis 0029003: 3rd point by Foram
		--	WHERE
		--		OM.Id = @rOrgId AND DM.Id IS NULL

		--END
		--ELSE
		--BEGIN --If DailyThought not Assign to particular day than insert into temp table and select from that
		--	DELETE FROM sCommunication.tDailyThoughtTemp WHERE OrgGroupId = @lOrgGroupId

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

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

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

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

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

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


GO
ALTER PROCEDURE [sCommunication].[pFeedbackAnalysisGet] 
    @rOrgGroupBatchId INT
	--,@rOrgGroupId smallint
	,@rFeedbackId BIGINT
	,@rFeedbackForId BIGINT
	,@rOrgId INT
	,@rBatchId INT
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT
		--A.Id As AcademicId,
		CASE FR.SourceTypeId
			WHEN 2001
				THEN A.Id
			WHEN 95
				THEN EM.Id
			END AS Id
		,CASE FR.SourceTypeId
			WHEN 2001
				THEN SM.Code
			WHEN 95
				THEN EM.Code
			END AS Code
		,CASE FR.SourceTypeId
			WHEN 2001
				THEN SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName
			WHEN 95
				THEN EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName
			END AS Name
		,SM.ID AS StudentID
	FROM sCommunication.tFeedback FB
	INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id
		AND FR.FeedbackForId = @rFeedbackForId
	LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = FR.SourceId
		AND FR.SourceTypeId = 95
		--AND EM.OrgId = @rOrgId -- Commented for Mantis 0029364 By Foram
	LEFT JOIN sStudent.tAcademic A ON A.Id = FR.SourceId
		AND FR.SourceTypeId = 2001
		--AND A.BatchId = @rBatchId -- Commented for Mantis 0029364 By Foram
	LEFT JOIN sStudent.tStudentMaster SM ON SM.ID = A.StudentID
	WHERE OrgGroupBatchId = @rOrgGroupBatchId
		AND FB.Id = @rFeedbackId
		AND ISNULL(EM.IsOtherUser, 0) = 0
END
GO
PRINT N'Altering Procedure [sCommunication].[pFeedbackDataGet]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackDataGet]
	  
        --@rFeedbackId bigint=0 ,
        @rOrgId int=0,
        @rBatchId int,
        @rOrgGroupBatchId int ,
        @rSourceId bigint=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	--Declare @lSourceTypeId smallint,@lFeedbackId  bigint=0 
	--SELECT @lFeedbackId=FB.Id FROM sCommunication.tFeedback FB
 --   INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id 
 --   WHERE OrgGroupBatchId=@rOrgGroupBatchId and IsClose=0 and IsPublish=1  AND AssignToSourceId =@rSourceId ORDER BY Title
 
	--Select @lSourceTypeId=ForSourceTypeId from sCommunication.tFeedbackFor where FeedbackId=@lFeedbackId
	
	Select 
		 (CASE ForSourceTypeId WHen  95
		 THEN
			(Select 
			 FirstName +' ' + MiddleName+' ' + LastName
			From sHrm.tEmployeeMaster Where  Id=FF.ForSourceId And FF.ForSourceTypeId=95 And  --OrgId=@rOrgId AND -- Commented for Mantis 0029364 By Foram
			ISNULL(IsOtherUser,0) = 0  )
		 WHEN  2001
		 THEN
			(Select
			 FirstName +' ' + MiddleName+' ' + LastName
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FF.ForSourceId ANd FF.ForSourceTypeId=2001)
		 Else
			FF.ForName
		 END) AS Name, 
		 
		 (CASE ForSourceTypeId WHen  95
		 THEN
			(Select 
			 Code
			From sHrm.tEmployeeMaster Where  Id=FF.ForSourceId And FF.ForSourceTypeId=95 And  --OrgId=@rOrgId AND -- Commented for Mantis 0029364 By Foram
			ISNULL(IsOtherUser,0) = 0  )
		 WHEN  2001
		 THEN
			(Select
			 SM.Code
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FF.ForSourceId ANd FF.ForSourceTypeId=2001)
		 Else
			FF.ForName
		 END) AS Code, 
		 
		 (CASE ForSourceTypeId WHen  95
		 THEN
			(Select 
			 Id
			From sHrm.tEmployeeMaster Where  Id=FF.ForSourceId And FF.ForSourceTypeId=95 And  --OrgId=@rOrgId AND -- Commented for Mantis 0029364 By Foram
			 ISNULL(IsOtherUser,0) = 0  )
		 WHEN  2001
		 THEN
			(Select
			 A.Id
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FF.ForSourceId ANd FF.ForSourceTypeId=2001)
		 Else
			0  
		 END) AS Id, 
		 FF.Id AS FeedbackForId,
		FB.Id AS FeedbackId,FB.Title ,
		FB.FeedbackTemplateId
	 FROM sCommunication.tFeedbackFor FF 
	 INNER JOIN sCommunication.tFeedback FB ON FB.Id=FF.FeedbackId
	 INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id
	 Where FB.OrgGroupBatchId=@rOrgGroupBatchId and IsClose=0 and IsPublish=1  AND AssignToSourceId =@rSourceId 
	 
	--If @lSourceTypeId=2001
	--BEGIN
	--	SELECT FB.Id AS FeedbackId,FB.Title,A.Id,Code+' - '+FirstName+' '+MiddleName+' '+LastName AS name 
	--	 FROM sCommunication.tFeedback FB
	--	--INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id 
	--	INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id
	--	INNER JOIN sCommunication.tFeedbackFor FO ON FO.FeedbackId=FB.ID
	--	INNER JOIN sStudent.tAcademic A  on FO.ForSourceId=A.Id
	--	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
	--	Where SM.OrgId=@rOrgId   And A.BatchId=@rBatchId
	--	And FB.OrgGroupBatchId=@rOrgGroupBatchId and IsClose=0 and IsPublish=1  AND AssignToSourceId =@rSourceId 
	
	-- END
	
	--else if  @lSourceTypeId=95
	--BEGIN
	--	SELECT FB.Id AS FeedbackId,FB.Title,EM.Id,Code+' - '+FirstName+' '+MiddleName+' '+LastName AS name 
	--	 FROM sCommunication.tFeedback FB
	--	--INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id 
	--	INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id
	--	INNER JOIN sCommunication.tFeedbackFor FO ON FO.FeedbackId=FB.ID
	--	INNER JOIN sHrm.tEmployeeMaster EM  on FO.ForSourceId=EM.Id
	--	Where EM.OrgId=@rOrgId  and  OrgGroupBatchId=@rOrgGroupBatchId And IsClose=0 and IsPublish=1 and AssignToSourceId =@rSourceId
	--END
	
	--else
	--BEGIN
		 
	--	SELECT FB.Id AS FeedbackId,FB.Title,FO.ForName AS name,0 AS Id
	--	 FROM sCommunication.tFeedback FB
	--	INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id 
	--	LEFT JOIN sCommunication.tFeedbackFor FO ON FO.FeedbackId=FB.ID  
	--	where   OrgGroupBatchId=@rOrgGroupBatchId and IsClose=0 and IsPublish=1  
	--	AND ISNULL(AssignToSourceId,0) =0 AND ISNULL(ASSIgntosourcetypeid,0)=0
		  
	--END  
END
GO
PRINT N'Altering Procedure [sEMeeting].[pMeetingTypeGet]...';


GO

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


GO

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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY

	IF (@rAutoId = 0)
	BEGIN
	 
	IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where Code = @rCode)
		BEGIN
			SELECT -101 as Result
			Return
		END
	IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where OrderIndex = @rOrderIndex)
		BEGIN
			SELECT -102 as Result
			Return
		END
	END
	ELSE
	    BEGIN
		IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where Code = @rCode AND AutoId<>@rAutoId)
		BEGIN
			SELECT -101 as Result
			Return
		END
		IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where OrderIndex = @rOrderIndex AND		AutoId<>@rAutoId)
		BEGIN
			SELECT -102 as Result
			Return
		END
		END

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

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


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

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	IF EXISTS (SELECT 1 from sEMeeting.tOnlineMeeting where MeetingTypeId = @rId)
	BEGIN
	SELECT -101 As Result
	END
	ELSE
	BEGIN
	IF EXISTS (SELECT 1 from sEMeeting.tMeetingTypeMaster where AutoId = @rId)
	BEGIN 
	Delete sEMeeting.tMeetingTypeMaster WHERE AutoId = @rId
	SELECT 1 As Result
	END
	END
END TRY
BEGIN CATCH 
		SELECT -1 AS Result
END CATCH
END
GO
PRINT N'Altering Procedure [sEMeeting].[pMeetingTypeMasterDetailGet]...';


GO
 
ALTER PROCEDURE [sEMeeting].[pMeetingTypeMasterDetailGet]
	 @rId smallint = 0,
	 @rTitle nvarchar(20) = ''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	If(@rId = 0) 
	BEGIN 
		 SELECT AutoId, Title, Code, OrderIndex, Description, IsObsolete
			from [sEMeeting].[tMeetingTypeMaster] MTM 
			 where (MTM.Title LIKE '%' + @rTitle + '%' OR (ISNULL(@rTitle,'') = '') OR @rTitle = '*')
			 Order By MTM.OrderIndex
	END
	ELSE
	BEGIN
		SELECT AutoId, Title, Code, OrderIndex, Description, IsObsolete
			from [sEMeeting].[tMeetingTypeMaster] where AutoId = @rId
	END
END TRY
BEGIN CATCH 
		SELECT -1 AS Result
END CATCH
END
GO
PRINT N'Altering Procedure [sEMeeting].[pOnlineMeetingGet]...';


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

BEGIN 
BEGIN TRY

	if(@rId = 0)
	BEGIN 
	SELECT 
			OM.Id,
			EM.FirstName +' '+ EM.LastName as Teacher,
			OMT.Title as MeetingType,
			CONVERT(NVARCHAR,OM.StartDate,3)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,3)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			OM.IsCompleted as StatusId,
		    ISNULL(OM.Title,'') as Title,
			OM.StartDate AS TeacherStartDate,
			OM.EndDate AS TeacherEndDate,
			OM.AssigneeId,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sSetup.tClassMaster CM ON OMS.ScopeSourceId = CM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sSetup.tDivisionMaster DM ON OMS.ScopeSourceId = DM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2005
			  UNION ALL
			  SELECT Title FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sSetup.tOrganizationMaster DM ON OMS.ScopeSourceId = DM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2021
			  UNION ALL
			  SELECT Code FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sSetup.tDepartmentMaster DM ON OMS.ScopeSourceId = DM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2017
			  UNION ALL
			  SELECT EmployeeName as Code FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sHrm.vEmployeeCommunication EM ON OMS.ScopeSourceId = EM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 95
			  UNION ALL
			  SELECT (Code+' - '+CONVERT(NVARCHAR(10),RollNo)+' - '+Name) as Code FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sStudent.vStudentAcademic SA ON OMS.ScopeSourceId = SA.AcademicId Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2003
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as Assignee 
	  FROM 
			sEMeeting.tOnlineMeeting OM
			
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId 
			INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
			INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=OM.AssigneeId
	  WHERE 
    (
        (OM.Title LIKE @rTitle OR ISNULL(@rTitle, '') = '')
        AND (
            (OM.StartDate >= @rFromDate OR ISNULL(@rFromDate, '') = '')
            AND (OM.StartDate <= @rToDate OR ISNULL(@rToDate, '') = '')
            OR
            (OM.EndDate >= @rFromDate OR ISNULL(@rFromDate, '') = '')
            AND (OM.EndDate <= @rToDate OR ISNULL(@rToDate, '') = '')
        )
        AND (OM.HostEmployeeId = @rEmployeeId OR @rEmployeeId = 0)
        AND (OM.MeetingTypeId = @rMeetingTypeId OR @rMeetingTypeId = 0)
        AND (OM.MeetingAccountId = @rOnlineMeetingAccountId OR @rOnlineMeetingAccountId = 0)
        AND (
            (OM.IsCompleted IN (549, 550, 551, 0) AND @rIsCompleted = 0)
            OR (OM.IsCompleted = @rIsCompleted AND @rIsCompleted IN (549, 550, 551))
        )
        AND (
            (OM.AssigneeId IN (1, 2, 3) AND @rAssigneeId = 1)
            OR (OM.AssigneeId = @rAssigneeId AND @rAssigneeId IN (2, 3))
        )
    )

ORDER BY
    OM.StartDate DESC
	SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2021

			UNION ALL

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

			UNION ALL

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

			UNION ALL

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

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

			UNION ALL

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

			UNION ALL

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

			UNION ALL

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

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


GO

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

BEGIN 

	if (@rId = 0)
		BEGIN
	  DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint,
	 @lClassName nvarchar(100)


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

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

			WHERE
				(
				(OM.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				AND (
						(OM.StartDate >= @rStartDate OR ISNULL(@rStartDate, '') = '')
						AND (OM.StartDate <= @rEndDate OR ISNULL(@rEndDate, '') = '')
						OR
						(OM.EndDate >= @rStartDate OR ISNULL(@rStartDate, '') = '')
						AND (OM.EndDate <= @rEndDate OR ISNULL(@rEndDate, '') = '')
					)
				AND ((OM.MeetingTypeId = @rMeetingTypeId)OR (ISNULL(@rMeetingTypeId,0)=0))
				AND ((Convert(int,OM.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = 0)
				)
				ORDER BY OM.StartDate DESC
			END
		
	IF (@rScopeSourceTypeId = 95)
	BEGIN 
	DECLARE @lOrgId1 int,@lDepartmentId1 int,@lEmployeeId1 bigint
	 SELECT @lOrgId1 = EC.OrgId, @lDepartmentId1 =EC.DepartmentId, @lEmployeeId1 = EC.EmployeeId
     FROM sHrm.vEmployeeCommunication EC
	 WHERE EC.Id = @rScopeSourceId
		SELECT 
			OM.Id,
			OMT.Title AS MeetingType,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			(CASE WHEN OM.IsCompleted=0 THEN 'Pending' WHEN OM.IsCompleted=550 THEN 'Completed'  WHEN OM.IsCompleted=551 THEN 'Cancel' END) AS Status,
			ISNULL(OM.Title,'') As Title,
			OM.StartDate AS TeacherStartDateTime,
			OM.EndDate AS TeacherEndDateTime
			FROM 
				sEMeeting.tOnlineMeeting OM
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId
				INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
				INNER JOIN (SELECT OMS.OnlineMeetingId FROM sEMeeting.tOnlineMeetingScope OMS
				WHERE (
				( 
				(OMS.ScopeSourceTypeId = 2021 AND OMS.ScopeSourceId =@lOrgId1 AND OMS.AssigneeId = 3) 
				OR
				(OMS.ScopeSourceTypeId = 2017 AND OMS.ScopeSourceId =@lDepartmentId1 AND OMS.AssigneeId = 3)
				OR
				(OMS.ScopeSourceTypeId = 95 AND OMS.ScopeSourceId =@lEmployeeId1 AND OMS.AssigneeId = 3)
				 ))
				) D
				ON D.OnlineMeetingId= OM.Id OR (OM.HostEmployeeId = @rScopeSourceId)
			WHERE
			(
			    (OM.MeetingTypeId = @rMeetingTypeId OR @rMeetingTypeId = 0)
			    AND (
			        (OM.StartDate >= @rStartDate OR ISNULL(@rStartDate, '') = '')
			        AND (OM.StartDate <= @rEndDate OR ISNULL(@rEndDate, '') = '')
			        OR
			        (OM.EndDate >= @rStartDate OR ISNULL(@rStartDate, '') = '')
			        AND (OM.EndDate <= @rEndDate OR ISNULL(@rEndDate, '') = '')
			    )
			    AND (Convert(int, OM.IsCompleted) = @rIsCompleted OR @rIsCompleted = 0)
			    AND (OM.Title LIKE '%' + @rTitle + '%' OR ISNULL(@rTitle, '') = '')
			)
			ORDER BY
			    OM.StartDate ASC;

		END
		END
	ELSE
	IF (@rScopeSourceTypeId = 2003)
	BEGIN 

	 DECLARE @lAcademicId2 bigint,@lStudentId2 bigint,@lClassId2 int,@lDivisionId2 int,@lOrgId2 int,@lDepartmentId2 int,@lEmployeeId2 bigint,
	 @lClassName2 nvarchar(100)


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



	SELECT
			OM.Id,
			OMT.Title AS MeetingType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'')  AS Teacher,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndTime,
			(CASE WHEN OM.IsCompleted=0 THEN 'Pending' WHEN OM.IsCompleted=550 THEN 'Completed'  WHEN OM.IsCompleted=551 THEN 'Cancel' END) AS Status,
			OM.MeetingTypeId AS MeetingTypeId,
			OM.IsDisplayMeetingId AS IsDisplayMeetingId,
			OM.MeetingId AS MeetingId,
			OM.MeetingPassword AS MeetingPassword,
			ISNULL(OM.IsMeetingStarted,'') AS IsMeetingStarted,
			OM.IsCompleted AS IsCompleted,
			ISNULL(OM.Description,'')AS Description,
			ISNULL(OM.Title,'') AS Title,
			ISNULL(OM.IsMeetingStarted,'') AS IsMeetingStarted,
			OM.IsMeetingCreated AS IsMeetingCreated,
			OM.IsReference,
			OM.IsResource
          FROM 
				sEMeeting.tOnlineMeeting OM
				
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId 
				INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
				INNER JOIN (SELECT OMS.OnlineMeetingId FROM sEMeeting.tOnlineMeetingScope OMS
				WHERE (
				( 
				(OMS.ScopeSourceTypeId = 2021 AND OMS.ScopeSourceId =@lOrgId AND OMS.AssigneeId = 2) 
				OR
				(OMS.ScopeSourceTypeId = 2017 AND OMS.ScopeSourceId =@lDepartmentId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2016 AND OMS.ScopeSourceId =@lClassId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2005 AND OMS.ScopeSourceId =@lDivisionId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2003 AND OMS.ScopeSourceId =@lAcademicId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2001 AND OMS.ScopeSourceId =@lAcademicId AND OMS.AssigneeId = 2)
				 ))
				) D
				ON D.OnlineMeetingId= OM.Id

            
            WHERE
				 OM.Id = @rId

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

			UNION ALL

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

			UNION ALL

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

			UNION ALL

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

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


GO


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

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


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

	--DECLARE @lAdmissionCategoryId int =  0
	--SET @lAdmissionCategoryId = [sCommon].[fGetIntIdForOrg](1,@rOrgId)
	
		if object_id('tempdb..#tTable') is not null
		BEGIN
			DROP TABLE #tTable
		END

		Create table #tTable(
			AcademicId bigint not null
		)

		Insert into #tTable
			select SA.AcademicId 
			FROM sFee.tFeeSetup FS
			INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId=FS.ClassId AND FS.BatchId = SA.BatchId AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
			where ((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			-- AND SA.AdmissionCategoryId=@lAdmissionCategoryId
			group by FS.ClassId,SA.AcademicId 

		--Create Table #ttemptable1
		--	(
		--		AcademicId bigint,
		--		PaidAmount int,
		--		PendingAmount int
		--	)
		--	Insert into #ttemptable1
		--	(
		--		AcademicId,
		--		PaidAmount,
		--		PendingAmount
		--	)
		--	Select SA.AcademicId , SUM(SF.PaidAmount) AS PaidAmount , SUM(SF.PendingAmount) AS PendingAmount
		--	From sStudent.vStudentAcademic SA 
		--	Inner Join sFee.tStudentFee SF ON SA.AcademicId=SF.AcademicId
		--	where SA.OrgId=9911 AND SA.BatchId=991100104
		--	Group by SA.AcademicId

		

	IF(@rType = 'FeeList')
	BEGIN

		if object_id('tempdb..#tempAcademicDetail') is not null
		BEGIN
			DROP TABLE #tempAcademicDetail
		END
		
		Create table #tempAcademicDetail(
			AcademicId bigint not null
		)

		SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
		INTO #tempReceiptDetail
					FROM sFee.tReceiptDetail RD
					INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					WHERE R.SourceTypeId = 2001
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					Group By R.SourceId,FS.Id

		SELECT Distinct SourceId INTO #tempReceipt FROM sFee.tReceipt


		INSERT INTO #tempAcademicDetail
		SELECT 
			SA1.AcademicId 
		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
		LEFT JOIN #tempReceiptDetail R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
		INNER JOIN #tempReceipt RE ON RE.SourceId = SA1.AcademicId
		WHERE 
			((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND SA1.StatusId =1
			AND FS1.IsOptional = 0
			AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
					
		INSERT INTO #tempAcademicDetail
		SELECT 
			SA1.AcademicId 
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
		LEFT JOIN #tempReceiptDetail R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
		INNER JOIN #tempReceipt RE ON RE.SourceId = SA1.AcademicId
		WHERE 
			((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND SA1.StatusId =1
			AND FS1.IsOptional = 1
			AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
		

		CREATE TABLE #tmp
		(
			AcademicId bigint,
			Amount decimal(12,2),
			VariableAmount decimal(12,2),
			AdditionalAmount decimal(12,2),
			DiscountAmount decimal(12,2),
			NotApplicableAmount decimal(12,2)
		)
		INSERT INTO #tmp
			Select SA.AcademicId  AS AcademicId 
			, SUM(FS1.Amount) AS Amount , Sum(FA1.VariableAmount) AS VariableAmount, SUM(FA1.AdditionalAmount)AS AdditionalAmount,SUM(FA1.DiscountAmount)AS DiscountAmount,
			SUM(FA1.NotApplicableAmount)AS NotApplicableAmount
			From sStudent.vStudentAcademic SA

			--Changes for pending fee minus count for mantis Id :0027388
			--LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId
			--LEFT JOIN sFee.tFeeSetup FS1 ON FA1.FeeSetupId = FS1.Id AND FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId  AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId AND FS1.Id = FA1.FeeSetupId
			INNER JOIN #tTable tmp1 ON tmp1.AcademicId = SA.AcademicId
		
			Where
			((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			group by FS1.ClassId,SA.AcademicId 

			SELECT COUNT(SA.AcademicId)AS TotalCount,COUNT(T.PaidCount) AS PaidCount,(COUNT(tmp.AcademicId)-COUNT(T.PaidCount))AS UnPaidCount
			, COUNT(PS.AcademicId) AS PartialCount
			FROM sStudent.vStudentAcademic SA 
			LEFT JOIN #tmp tmp ON SA.AcademicId = tmp.AcademicId 
			AND ISNULL(((ISNULL(Amount,0) + ISNULL(VariableAmount,0)+ ISNULL(0,AdditionalAmount)) - (DiscountAmount + NotApplicableAmount)),1) <> 0 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			Inner Join #tTable FS  on  FS.AcademicId=SA.AcademicId
			LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,SA.AcademicId AS AcademicId FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId
			)T ON T.AcademicId = SA.AcademicId 

			LEFT JOIN #tempAcademicDetail PS ON PS.AcademicId=SA.AcademicId
			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND SA.StatusId =1
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			--AND ACM.Code Like '%General%' 
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0	
			DROP TABLE  #tmp
		END
	ELSE IF(@rType = 'FeeGraph')
		BEGIN
		
		CREATE TABLE #tmpData
		(
			AcademicId bigint,
			Amount decimal(12,2),
			VariableAmount decimal(12,2),
			AdditionalAmount decimal(12,2),
			DiscountAmount decimal(12,2),
			NotApplicableAmount decimal(12,2)
		)
		INSERT INTO #tmpData
			Select SA.AcademicId  AS AcademicId 
			, SUM(FS1.Amount) AS Amount , Sum(FA1.VariableAmount) AS VariableAmount, SUM(FA1.AdditionalAmount)AS AdditionalAmount,SUM(FA1.DiscountAmount)AS DiscountAmount,
			SUM(FA1.NotApplicableAmount)AS NotApplicableAmount
			From sStudent.vStudentAcademic SA

			--Changes for pending fee minus count for mantis Id :0027388
			--LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId
			--LEFT JOIN sFee.tFeeSetup FS1 ON FA1.FeeSetupId = FS1.Id AND FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId  AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId AND FS1.Id = FA1.FeeSetupId
			INNER JOIN #tTable tmp1 ON tmp1.AcademicId = SA.AcademicId
		
			Where
			((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			group by FS1.ClassId,SA.AcademicId 


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

			DROP TABLE #tmpData
		
		END
	ELSE IF (@rType = 'FeeListDetails')
		BEGIN

		if object_id('tempdb..#tempAcademicDetail') is not null
		BEGIN
			DROP TABLE #tempAcademicDetail1
		END
		
		Create table #tempAcademicDetail1(
			AcademicId bigint not null
		)

		SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
		INTO #tempReceiptDetail1
					FROM sFee.tReceiptDetail RD
					INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					WHERE R.SourceTypeId = 2001
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					Group By R.SourceId,FS.Id

		SELECT Distinct SourceId INTO #tempReceipt1 FROM sFee.tReceipt

		INSERT INTO #tempAcademicDetail1
		SELECT 
			SA1.AcademicId 
		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
		LEFT JOIN #tempReceiptDetail1 R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
		INNER JOIN #tempReceipt1 RE ON RE.SourceId = SA1.AcademicId
		WHERE 
			((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND SA1.StatusId =1
			AND FS1.IsOptional = 0
			AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
					
		INSERT INTO #tempAcademicDetail1
		SELECT 
			SA1.AcademicId 
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
		LEFT JOIN #tempReceiptDetail1 R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
		INNER JOIN #tempReceipt1 RE ON RE.SourceId = SA1.AcademicId
		WHERE 
			((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND SA1.StatusId =1
			AND FS1.IsOptional = 1
			AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
		

		SELECT F.RollNo,F.Name,F.Code,F.Pending,F.[Partial],F.[Status],F.ClassDivision
		FROM
		(

		SELECT SA.RollNo,SA.Name,SA.Code, ISNULL(T.AcademicId,0) AS Pending, ISNULL(PS.AcademicId,0) AS [Partial],'' AS [Status]
			,SA.ClassName+'/'+SA.DivisionName AS ClassDivision,
			(
				Select (SUM(FS1.Amount)+Sum(FA1.VariableAmount)+ SUM(FA1.AdditionalAmount)) - (SUM(FA1.DiscountAmount)+ SUM(FA1.NotApplicableAmount)) 
				From sFee.tFeeAllocation FA1
				INNER JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId AND FA1.FeeSetupId = FS1.Id
				Where FA1.SourceId = SA.AcademicId 
			) AS IsFeePayAmount
			--,ISNULL(FS1.PaidAmount,0) AS PaidAmount ,ISNULL(FS1.PendingAmount,0)AS PendingAmount
			FROM sStudent.vStudentAcademic SA 
			Inner Join #tTable FS  on  FS.AcademicId=SA.AcademicId
			--LEFT Join #ttemptable1 FS1 ON FS1.AcademicId=SA.AcademicId
			LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,SA.AcademicId AS AcademicId, SA.Code,SA.Name FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId, SA.Code,SA.Name
			)T ON T.AcademicId = SA.AcademicId
			LEFT JOIN #tempAcademicDetail1 PS ON PS.AcademicId=SA.AcademicId

			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND SA.StatusId =1
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))	 			
			) AS F 
			WHERE ISNULL(F.IsFeePayAmount,1) <> 0
		END

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

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

			SELECT Isnull(Sum(R.ReceiptAmount),0.00) as UptodateCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate<=CAST(GETDATE() as DATE))
		END
		--Drop Table #ttemptable1
		Drop Table #tTable
END
GO
PRINT N'Altering Procedure [sFee].[pRptFeeReceiptDoubleA5WithNextPendingFeeGet]...';


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

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

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

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

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

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


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

BEGIN  
	
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	
	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 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


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

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


GO


ALTER PROCEDURE [sPurchase].[pDependentConfigurationGet]
	  @rOrgId bigint,
	  @rOrgGroupId int,
	  @rUserId bigint,
	  @rScreenId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		  SELECT CL.Title,
		       CM.Title AS ConfigTitle,
			   CM.ItemKey,
			   CASE WHEN  CS.ItemValue IS NULL THEN CM.ItemValue  ELSE Isnull(CS.ItemValue,0) END AS ItemValue  
	      FROM sConfig.tConfigurationMaster CM   
		  INNER JOIN  sConfig.tConfigurationLevelMaster CL ON CL.Id=CM.ConfigurationLevelId 
		  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id=CS.ConfigurationId
		  AND  CS.SourceTypeId=(CASE  WHEN CL.Id =1 THEN 1016 wheN cl.Id=5 THEN 2010 when cL.Id=4 then 95   END) 
		  AND  CS.SourceId=(CASE  WHEN CL.Id =1 THEN @rOrgId wheN cl.Id=5 THEN @rOrgGroupId when cL.Id=5 then @rUserId END) 
		  WHERE  IsObsolete=0 AND ScreenId = @rScreenId 
		  ORDER BY CL.Id
	END TRY

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


GO

--exec [sPurchase].[pGoodsReceivedNoteSearchGet] null,991100001,null,9911,'2023-01-01','2023-12-30',1,10,null
ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar = '',
	@rOrgGroupId int,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
	@rPageNo int,
	@rPageSize int,
	@rStatusId smallint = null

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


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



		WHERE 
				((GRN.GRNNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((GRN.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND GRN.IsObsolete = 0
				AND ((Cast(GRN.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(GRN.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))

	    Select t.* From (
			Select ROW_NUMBER() Over (
			Order by GRN.Id desc  
			) AS 'RowNum',GRN.Id,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.VendorId,
				GRN.GRNNumber as Number,
				GRN.RequestedBy, 
				GRN.LocationId, 
				GRN.PODueDate,
				ISNULL(SM.Title,'') as Status,
				VM.Code AS VendorCode,
			    VM.Title AS VendorName,
				PR.Number as PurchaseNumber,
				PO.RefNumber as PurchaseOrderNumber

	    FROM		
				sPurchase.tGoodsReceivedNote GRN (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on GRN.StatusId = SM.Id
				Left JOIN sProcurement.tVendorMaster  VM on GRN.VendorId = VM.ID
				Left Join [sPurchase].[tPurchaseRequest] PR on PR.Id = GRN.PurchaseRequestId
				Left Join [sPurchase].[tPurchaseOrder] PO on PO.Id = GRN.PurchaseOrderId
		WHERE 
				((GRN.GRNNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((GRN.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND GRN.IsObsolete = 0
				AND ((Cast(GRN.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(GRN.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
					)t Where t.RowNum Between
		((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

		SELECT @TotalRecords as TotalRecords

	 END TRY

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


GO

--exec [sPurchase].[pGoodsReceivedNoteSearchSRGet] null,991100001,null,9911,'2023-12-01','2023-12-30',1,10,null
ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchSRGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar = '',
	@rOrgGroupId int,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
	@rPageNo int,
	@rPageSize int,
	@rStatusId smallint = null

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
					DECLARE @TotalRecords BIGINT;
		            -- Get the total number of records
					SELECT @TotalRecords = COUNT(*) FROM sPurchase.tGoodsReceivedNote GRN (nolock)

					WHERE 
							((GRN.GRNNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   							AND ((GRN.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   							--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   							AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
							AND ((GRN.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
							AND GRN.IsObsolete = 0 AND GRN.StatusId = 3
							AND GRN.Id IN
							(select distinct GRN12.Id from sPurchase.tSalesReturnDetail SRD
							Inner Join sPurchase.tSalesReturn SR on SR.Id = SRD.SalesReturnId
							Inner Join sPurchase.tGoodsReceivedNote GRN12 on Sr.GoodsReceivedNoteId = Grn12.Id
							Inner Join [sPurchase].[tGoodsReceivedNoteDetail] GRND on SRD.GoodsReceivedNoteDetailId = GRND.Id
							AND GRND.GoodsReceivedNoteId = GRN12.Id
							Group by GRN12.Id
							having  Sum(SRD.RejectedQty) < (select Sum(QCD1.RejectedQty) from sPurchase.tGoodsReceivedNote GRN12
							INNER JOIN   sPurchase.tQualityCheck QC1 on QC1.GoodsReceivedNoteId = GRN12.Id
							INNER JOIN   sPurchase.tQualityCheckDetail QCD1 on QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
							where GRN12.Id = GRN.Id))
							AND ((Cast(GRN.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
							AND((Cast(GRN.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))


					Select t.* From (
						Select ROW_NUMBER() Over (
						Order by GRN.Id desc  
						) AS 'RowNum',GRN.Id,
							GRN.GRNNumber as Number,
							GRN.RequestedBy, 
							GRN.LocationId, 
							GRN.PODueDate,
							ISNULL(SM.Title,'') as Status,
							(select Sum(QCD1.RejectedQty) from sPurchase.tGoodsReceivedNote GRN12
							INNER JOIN   sPurchase.tQualityCheck QC1 on QC1.GoodsReceivedNoteId = GRN12.Id
							INNER JOIN   sPurchase.tQualityCheckDetail QCD1 on QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
							where GRN12.Id = GRN.Id) as RejectedQty

					FROM		
							sPurchase.tGoodsReceivedNote GRN (nolock)
							Left Join [sWf].[tWfStatusMaster] SM on GRN.StatusId = SM.Id


					WHERE 
							((GRN.GRNNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   							AND ((GRN.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   							--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   							AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
							AND ((GRN.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
							AND GRN.IsObsolete = 0 AND GRN.StatusId = 3
							AND GRN.Id IN
							(select distinct GRN12.Id from sPurchase.tGoodsReceivedNote GRN12
							INNER JOIN   sPurchase.tQualityCheck QC1 on QC1.GoodsReceivedNoteId = GRN12.Id
							INNER JOIN   sPurchase.tQualityCheckDetail QCD1 on QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
							where GRN12.Id = GRN.Id
							Group by GRN12.Id
							having  (ISNULL(Sum(QCD1.RejectedQty),0) >(
							select ISNULL(Sum(SRD.RejectedQty),0) from sPurchase.tSalesReturnDetail SRD
							Inner Join sPurchase.tSalesReturn SR on SR.Id = SRD.SalesReturnId
							Inner Join sPurchase.tGoodsReceivedNote GRN1 on Sr.GoodsReceivedNoteId = Grn1.Id
							Inner Join [sPurchase].[tGoodsReceivedNoteDetail] GRND on SRD.GoodsReceivedNoteDetailId = GRND.Id
							AND GRND.GoodsReceivedNoteId = GRN1.Id))
							)
							AND ((Cast(GRN.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
							AND((Cast(GRN.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
								)t Where t.RowNum Between
							((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

				SELECT @TotalRecords as TotalRecords
	 END TRY

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


GO

--exec [sPurchase].[pGoodsReceivedNoteSRGet] 991100003
ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSRGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY

		if((Select (select Sum(QCD1.RejectedQty) from sPurchase.tGoodsReceivedNote GRN12
			    INNER JOIN   sPurchase.tQualityCheck QC1 on QC1.GoodsReceivedNoteId = GRN12.Id
			    INNER JOIN   sPurchase.tQualityCheckDetail QCD1 on QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
				where GRN12.Id = @rId) -
				 (select ISNULL(Sum(SRD.RejectedQty),0) from sPurchase.tSalesReturnDetail SRD
				Inner Join sPurchase.tSalesReturn SR on SR.Id = SRD.SalesReturnId
				Inner Join [sPurchase].[tGoodsReceivedNoteDetail] GRND on SRD.GoodsReceivedNoteDetailId = GRND.Id
				AND GRND.GoodsReceivedNoteId = @rId
				where SR.GoodsReceivedNoteId = @rId)) = 0)
		Begin
			Select -101
		End
		Else
		Begin
			select Distinct GRN.Id as GoodsReceivedNoteId,
					GRN.GRNNumber,
					GRN.OrgGroupId,
					GRN.LocationId,
					GRN.PurchaseRequestId,
					GRN.PurchaseOrderId,
					GRN.VendorId,
					GRN.RequestedBy,
					GRN.BillToAddress,
					GRN.StatusId,
					GRN.PODueDate,
					PO.RefNumber as PurchaseOrderNumber,
					ISNULL(SM.Title,'') as Status,
					VM.Title AS VendorName 
			from   [sPurchase].[tGoodsReceivedNote] GRN(nolock) 
				   INNER JOIN sPurchase.tQualityCheck QC on QC.GoodsReceivedNoteId = GRN.Id
				   INNER JOIN sPurchase.tPurchaseOrder PO on PO.Id = GRN.PurchaseOrderId
				   LEFT JOIN  sProcurement.tVendorMaster  VM on GRN.VendorId = VM.ID
				   LEFT Join  sWf.tWfStatusMaster SM ON SM.Id = GRN.StatusId
			where  GRN.Id=@rId AND GRN.IsObsolete = 0 AND GRN.StatusId = 3

			select Distinct GRND.Id as GoodsReceivedNoteDetailId,
				   GRND.GoodsReceivedNoteId,
				   GRND.PurchaseOrderDetailId,
				   GRND.OrgGroupId,
				   SUMa.Id AS UnitTypeId,
				   GRND.StockItemId,
				   GRND.POQty,
				   GRND.ReceivedQty,
				   GRND.PreviousGRNQty,
				   GRND.UnitPrice,
				   GRND.Remark, 
				 --  (select Sum(QCD1.RejectedQty) from sPurchase.tGoodsReceivedNote GRN12
				 --   INNER JOIN   sPurchase.tQualityCheck QC1 on QC1.GoodsReceivedNoteId = GRN12.Id
				 --   INNER JOIN   sPurchase.tQualityCheckDetail QCD1 on QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
					--where GRN12.Id = GRN.Id) AS RejectedQty,
					(select Sum(QCD1.RejectedQty) from sPurchase.tGoodsReceivedNote GRN12
					INNER JOIN   sPurchase.tQualityCheck QC1 on QC1.GoodsReceivedNoteId = GRN12.Id
					INNER JOIN   sPurchase.tQualityCheckDetail QCD1 on QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
					where GRN12.Id = GRN.Id) -
					 (select ISNULL(Sum(SRD.RejectedQty),0) from sPurchase.tSalesReturnDetail SRD
					Inner Join sPurchase.tSalesReturn SR on SR.Id = SRD.SalesReturnId
					where SR.GoodsReceivedNoteId = GRN.Id And SRD.GoodsReceivedNoteDetailId = GRND.Id) 
					AS RejectedQty,
				   '' AS ReasonForRejection,
				   SIM.Code	AS StockItemCode,
				   SIM.Title AS StockItemName,
				   SUMa.Code AS UOM,
				   SCM.Id as CategoryId,
				   SCM.Title as CategoryName,
				   0 as SubCategoryId
			from   [sPurchase].[tGoodsReceivedNoteDetail] GRND (nolock)
				   INNER JOIN	sPurchase.tGoodsReceivedNote GRN	ON GRN.Id = GRND.GoodsReceivedNoteId AND GRN.IsObsolete = 0
				   INNER JOIN sPurchase.tQualityCheck QC on QC.GoodsReceivedNoteId = GRN.Id
				   INNER JOIN   sPurchase.tQualityCheckDetail QCD on QCD.QualityCheckId = QC.Id AND QCD.GoodsReceivedNoteDetailId = GRND.ID
				   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId 
				   INNER JOIN   sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
				   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			where  GRND.GoodsReceivedNoteId=@rId AND QCD.RejectedQty > 0 AND GRN.StatusId = 3
		End
	END TRY

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


GO

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

BEGIN
	BEGIN TRY
		If Exists(select PO.Id
		from   [sPurchase].[tPurchaseOrder] PO(nolock) 
		Inner Join [sPurchase].[tGoodsReceivedNote] GRN on GRN.PurchaseOrderId = PO.Id AND GRN.StatusId in (1,2)
		Where PO.Id = @rId)
		Begin
			Select -101
		End
		Else
		Begin
			select PO.Id as PurchaseOrderId,
				   PO.RefNumber as PurchaseOrderNumber,
				   PO.PurchaseRequestId,
				   PO.RequestedBy,
				   PO.StatusId,
				   PO.VendorId,
				   PO.LocationId,
				   PO.OrgGroupId,
				   PO.PODate as PODueDate,
				   PO.BillToAddress,
				   PO.ShipToAddress,
				   PO.RequiredBy,
				   ISNULL(SM.Title,'') as Status,
				   VM.Code AS VendorCode,
				   VM.Title AS VendorName,
				   PR.Number As PurchaseRequestNumber 
			from   [sPurchase].[tPurchaseOrder] PO(nolock) 
				   Left Join [sPurchase].[tPurchaseRequest] PR ON PR.ID = PO.PurchaseRequestId
				   Left JOIN sProcurement.tVendorMaster  VM on PO.VendorId = VM.ID 
				   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
			where  PO.Id=@rId AND PO.IsObsolete = 0 AND PO.StatusId = 3

			Declare @PreviousGrnQty int,@UnitPrice int
			--Select @PreviousGrnQty = Sum(GRND.ReceivedQty)
			--from [sPurchase].[tGoodsReceivedNote] GRN 
			--Left Join sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id
			--where GRN.PurchaseOrderId = @rId

			select Distinct POD.Id as PurchaseOrderDetailId,
				   POD.PurchaseOrderId,
				   POD.OrgGroupId,
				   POD.PurchaseRequestDetailId,
				   POD.StockItemId,
				   POD.TotalQty as POQty,
				   POD.Remark, 
				   SUMa.Id AS UnitTypeId,
				   SIM.Code				AS StockItemCode,
				   SIM.Title				AS StockItemName,
				   SUMa.Code				AS UOM,
				   SCM.Id as CategoryId,
				   SCM.Title as CategoryName,
				   0 as SubCategoryId,
				   Cast((POD.TotalQty - (Select Sum(GRND.ReceivedQty)
					from [sPurchase].[tGoodsReceivedNote] GRN 
					Left Join sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id
					Where GRND.PurchaseOrderDetailId = POD.Id AND GRN.PurchaseOrderId = PO.Id AND GRN.StatusID <> 4)) as decimal) as ReceivedQty ,
				   (Select Sum(GRND.ReceivedQty)
					from [sPurchase].[tGoodsReceivedNote] GRN 
					Left Join sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id
					Where GRND.PurchaseOrderDetailId = POD.Id AND GRN.PurchaseOrderId = PO.Id AND GRN.StatusID <> 4) as PreviousGRNQty,
				   (SELECT QRD.TargetPrice FROM [sPurchase].[tQuotationRequestDetail] QRD
					Inner Join [sPurchase].[tQuotationRequest] QR ON QR.Id = QRD.QuotationRequestId
					Where QRD.StockItemId = POD.StockItemId AND POD.PurchaseRequestDetailId = QRD.PurchaseRequestDetailId
					AND QR.PurchaseRequestId = PO.PurchaseRequestId) as UnitPrice
			from   [sPurchase].[tPurchaseOrderDetail] POD (nolock)
				   Inner JOIN	sPurchase.tPurchaseOrder PO	ON PO.Id = POD.PurchaseOrderId AND PO.IsObsolete = 0 AND PO.StatusId = 3
				   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = POD.StockItemId 
				   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
				   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			where  POD.PurchaseOrderId=@rId     
		End
		
	END TRY

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

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


GO


--exec [sPurchase].[pPurchaseOrderApprovedSearchGet] '',991100001,'',9911,'2023-01-01','2023-12-01',1,10,null
ALTER PROCEDURE [sPurchase].[pPurchaseOrderApprovedSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar = '',
	@rOrgGroupId int,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
	@rPageNo int,
	@rPageSize int,
	@rStatusId smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tPurchaseOrder PO (nolock)

		WHERE 
				((PO.RefNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PO.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PO.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PO.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PO.IsObsolete = 0 and PO.StatusId = 3
				AND PO.Id Not in (Select distinct PO.Id from sPurchase.tPurchaseOrder PO
				Inner Join [sPurchase].[tGoodsReceivedNote] GRN ON GRN.PurchaseOrderId = PO.Id
				Inner Join sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id AND GRND.PreviousGRNQty+GRND.ReceivedQty >= GRND.POQty
				Where Grn.PurchaseOrderId = PO.Id AND GRN.StatusID <> 4)
				AND ((Cast(PO.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(PO.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))


	    Select t.* From (
			Select ROW_NUMBER() Over (
			Order by PO.Id desc  
			) AS 'RowNum',
				PO.Id, 
				PO.RefNumber as Number,
				PO.RequestedBy, 
				PO.LocationId, 
				PO.PODate,
				ISNULL(SM.Title,'') as Status
		FROM		
				sPurchase.tPurchaseOrder PO (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on PO.StatusId = SM.Id
		WHERE 
				((PO.RefNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PO.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PO.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PO.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PO.IsObsolete = 0 and PO.StatusId = 3
				AND PO.Id Not in (Select distinct PO.Id from sPurchase.tPurchaseOrder PO
				Inner Join [sPurchase].[tGoodsReceivedNote] GRN ON GRN.PurchaseOrderId = PO.Id
				Inner Join sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id AND GRND.PreviousGRNQty+GRND.ReceivedQty >= GRND.POQty
				Where Grn.PurchaseOrderId = PO.Id AND GRN.StatusId <> 4)
				AND ((Cast(PO.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(PO.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
					)t Where t.RowNum Between
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords as TotalRecords

	 
	 END TRY

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


GO




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

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			If Not Exists(SELECT SR.Id 
			FROM [sPurchase].[tSalesReturn] SR
			INNER JOIN [sPurchase].[tGoodsReceivedNote] GRN on SR.GoodsReceivedNoteId = GRN.Id
			INNER JOIN [sPurchase].[tQualityCheck] QC on GRN.Id = QC.GoodsReceivedNoteId
			Where QC.Id = @rId)
			Begin
				CREATE TABLE #temp_table (
					OrgGroupId SMALLINT,
					LocationId INT,
					StockItemId BIGINT,
					AcceptedQty decimal(12,2),
					Operation nvarchar(20),
					UserId BIGINT
				);

				Insert Into #temp_table
				Select QCD.OrgGroupId,@rLocationId,QCD.StockItemId,
				CASE
				WHEN QCD.AcceptedQty > DL.AcceptedQty THEN QCD.AcceptedQty - DL.AcceptedQty
				ELSE DL.AcceptedQty - QCD.AcceptedQty
				END,
				CASE
				WHEN QCD.AcceptedQty > DL.AcceptedQty THEN '-'
				ELSE '+'
				END,
				@rUserId 
				from sPurchase.tQualityCheckDetail QCD
				Inner Join @rDetailList DL ON DL.StockItemId = QCD.StockItemId and QCD.QualityCheckId = @rId
				where QualityCheckId = @rId

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

				delete from sPurchase.tQualityCheckDetail
				where Id not in(select Id from @rDetailList)
				and QualityCheckId = @rId

				update sPurchase.tQualityCheckDetail
				set
				GoodsReceivedNoteDetailId = DL.GoodsReceivedNoteDetailId,
				StockItemId = DL.StockItemId,
				POQty = DL.POQty,
				ReceivedQty = DL.ReceivedQty,
				AcceptedQty = DL.AcceptedQty,
				RejectedQty = DL.RejectedQty,
				ReasonForRejection = DL.ReasonForRejection,
				UpdatedUserId = @rUserId,
				UpdatedDateTime = GETUTCDATE()
				from @rDetailList DL
				inner join sPurchase.tQualityCheckDetail QC ON DL.ID = QC.Id
				where QC.QualityCheckId = @rId

				DECLARE @lNextNumberQCD BIGINT	 
				EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQualityCheckDetail',@lNextNumber = @lNextNumberQCD output
				set @lNextNumberQCD=@lNextNumberQCD-1
																																		INSERT INTO sPurchase.tQualityCheckDetail
			(
				Id,
				OrgGroupId,
				QualityCheckId,
				GoodsReceivedNoteDetailId,
				StockItemId,
				POQty,
				ReceivedQty,
				AcceptedQty,
				RejectedQty,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberQCD+Id,
					@rOrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tQualityCheckDetail QC ON DL.ID = QC.Id
			where QC.QualityCheckId = @rId)

				set @lNextNumberQCD=@lNextNumberQCD+(select Count(Id) from @rDetailList where Id not in(Select DL.Id from @rDetailList DL
				inner join sPurchase.tQualityCheckDetail QC ON DL.ID = QC.Id
				where QC.QualityCheckId = @rId))
				EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQualityCheckDetail', @rCurrentNumber = @lNextNumberQCD
			
				UPDATE  sProcurement.tStockBatch
				SET  AvailableQuantity = ISNULL(AvailableQuantity,0) + tt.AcceptedQty,
					UpdatedUserId = @rUserId,
					UpdatedDateTime = sCommon.fGetDate()
				FROM sProcurement.tStockBatch SB
				Inner Join #temp_table tt ON SB.Id = tt.StockItemId
				WHERE  
				(SB.StoreLocationId = tt.LocationId OR tt.LocationId = 0) AND
				(SB.StockItemId = tt.StockItemId) AND
				--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
				--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
					SB.OrgGroupId = @rOrgGroupId
					And tt.Operation = '+'

				UPDATE  sProcurement.tStockBatch
				SET  AvailableQuantity = ISNULL(AvailableQuantity,0) - tt.AcceptedQty,
					UpdatedUserId = @rUserId,
					UpdatedDateTime = sCommon.fGetDate()
				FROM sProcurement.tStockBatch SB
				Inner Join #temp_table tt ON SB.Id = tt.StockItemId
				WHERE  
				(SB.StoreLocationId = tt.LocationId OR tt.LocationId = 0) AND
				(SB.StockItemId = tt.StockItemId) AND
				--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
				--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
					SB.OrgGroupId = @rOrgGroupId
					And tt.Operation = '-'

				select @rId
			End
			select -101
		End
		Else
		Begin
			If Not Exists(SELECT SR.Id 
			FROM [sPurchase].[tSalesReturn] SR
			INNER JOIN [sPurchase].[tGoodsReceivedNote] GRN on SR.GoodsReceivedNoteId = GRN.Id
			INNER JOIN [sPurchase].[tQualityCheck] QC on GRN.Id = QC.GoodsReceivedNoteId
			Where QC.Id = @rId)
			Begin

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

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

	 			INSERT INTO sPurchase.tQualityCheckDetail
				(
					Id,
					OrgGroupId,
					QualityCheckId,
					GoodsReceivedNoteDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					ReasonForRejection,
					CreatedUserId,
					CreatedDateTime
				)
				select	@lNextNumberQCDD+Id,
						@rOrgGroupId,
						@rId,
						GoodsReceivedNoteDetailId,
						StockItemId,
						POQty,
						ReceivedQty,
						AcceptedQty,
						RejectedQty,
						ReasonForRejection,
						@rUserId, 
						GETUTCDATE() 
				from @rDetailList
						
				set @lNextNumberQCDD=@lNextNumberQCDD+(select Count(Id) from @rDetailList)
				EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQualityCheckDetail', @rCurrentNumber = @lNextNumberQCDD

				UPDATE  sProcurement.tStockBatch
					SET  AvailableQuantity = ISNULL(AvailableQuantity,0) + QC.AcceptedQty,
						UpdatedUserId = @rUserId,
						UpdatedDateTime = sCommon.fGetDate()
					FROM sProcurement.tStockBatch SB
					Inner Join sPurchase.tQualityCheckDetail QC ON SB.Id = QC.StockItemId
					WHERE  
				(SB.StoreLocationId = @rLocationId OR @rLocationId = 0) AND
				(SB.StockItemId = QC.StockItemId) AND
				--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
				--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
					SB.OrgGroupId = @rOrgGroupId

				select @rId
			End
			select -101;
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

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

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

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

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


GO

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

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

		select QCD.Id,
			   QCD.QualityCheckId,
			   QCD.GoodsReceivedNoteDetailId,
			   QCD.OrgGroupId,
			   SUMa.Id AS UnitTypeId,
			   QCD.StockItemId,
			   QCD.POQty,
			   (
			   (Select GRND.ReceivedQty  from [sPurchase].[tGoodsReceivedNoteDetail] GRND
			   where GRND.Id = QCD.GoodsReceivedNoteDetailId AND GRND.GoodsReceivedNoteId = QC.GoodsReceivedNoteId)-
			   (SELECT Sum(QCD1.AcceptedQty + QCD1.RejectedQty)
				FROM [sPurchase].[tQualityCheckDetail] QCD1 
				Inner JOIN	sPurchase.tQualityCheck QC1	ON QC1.Id = QCD1.QualityCheckId AND QC1.IsObsolete = 0 
				where QC1.GoodsReceivedNoteId = QC.GoodsReceivedNoteId 
				GROUP BY QC1.GoodsReceivedNoteId))
				+((SELECT Sum(QCD2.AcceptedQty + QCD2.RejectedQty)
				FROM [sPurchase].[tQualityCheckDetail] QCD2 
				where QCD2.Id = QCD.Id 
				GROUP BY QCD2.Id)) 
				as ReceivedQty,
			   QCD.AcceptedQty,
			   QCD.RejectedQty,
			   QCD.ReasonForRejection, 
			   SCM.Id as CategoryId,
			   SCM.Title as CategoryName,
			   0 as SubCategoryId,
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tQualityCheckDetail] QCD (nolock)
			   Inner JOIN	sPurchase.tQualityCheck QC	ON QC.Id = QCD.QualityCheckId AND QC.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QCD.StockItemId 
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  QCD.QualityCheckId=@rId


	END TRY

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


GO

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

BEGIN
	BEGIN TRY
		select  SR.Id,
				SR.SRNumber,
				SR.OrgGroupId,
				SR.LocationId,
				SR.GoodsReceivedNoteId,
				SR.PurchaseOrderId,
				SR.VendorId,
				SR.RequestedBy,
				ISNULL(GRN.GRNNumber,'') as GRNNumber,
				SR.StatusId,
				ISNULL(SM.Title,'') as Status,
				VM.Title AS VendorName,
				PO.RefNumber as PurchaseOrderNumber
		from   [sPurchase].[tSalesReturn] SR(nolock) 
		Left Join [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = SR.GoodsReceivedNoteID
		left JOIN sPurchase.tPurchaseOrder PO on PO.Id = SR.PurchaseOrderId
		Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = SR.StatusId
		LEFT JOIN  sProcurement.tVendorMaster  VM on SR.VendorId = VM.ID
		where  SR.Id=@rId AND SR.IsObsolete = 0

		select SRD.Id,
			   SRD.SalesReturnId,
			   SRD.GoodsReceivedNoteDetailId,
			   SRD.OrgGroupId,
			   SRD.StockItemId,
			   SRD.POQty,
			   SRD.ReceivedQty,
			   SRD.RejectedQty,
			   SUMa.Id AS UnitTypeId,
			   SRD.CreditNoteIssueDate,
			   SRD.ReasonForRejection, 
			   SIM.Code	AS StockItemCode,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM,
			   SCM.Id as CategoryId,
			   SCM.Title as CategoryName,
			   0 as SubCategoryId,
			   (select Sum(QCD1.RejectedQty) from sPurchase.tQualityCheck QC1
			    INNER JOIN   sPurchase.tQualityCheckDetail QCD1 on QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
				AND QCD1.GoodsReceivedNoteDetailId = SRD.GoodsReceivedNoteDetailId
				where QC1.GoodsReceivedNoteId = SR.GoodsReceivedNoteId) AS GRNRejectedQty
		from   [sPurchase].[tSalesReturnDetail] SRD (nolock)
			   Inner JOIN	sPurchase.tSalesReturn SR	ON SR.Id = SRD.SalesReturnId AND SR.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = SRD.StockItemId 
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  SRD.SalesReturnId=@rId

	END TRY

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


GO

ALTER PROCEDURE [sStudent].[pOnlineRegistrationStudentAdd]
	 
	@rId bigint,
	@rCode nvarchar(20),
	@rRegistrationNumber nvarchar(20),
	--@rNumber bigint,
	@rFirstName nvarchar(100),
	@rMiddleName nvarchar(100),
	@rLastName nvarchar(100),
	@rOrgId int,
	@rAdmissionCategoryId int,
	@rStatusId smallint,
	@rRecordStatusId smallint,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupBatchId int =0,
	@OutStudentId BIGINT = NULL OUTPUT,
	--@rSUId nvarchar(20) = '',
	@rOrgGroupId int = 0,
	--@rMobileNo nvarchar(50)='',
	@rStudentGroupId int=0,
	@rStudentOtherGroupId int=0,
	@rDateOfBirth Date=NULL,
    @rGenderId int=0,
    @rAcademicId bigint = 0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=0,
	@rBatchId int=0,
	@rStudentStatusId int,
	@rStudentPhoto varbinary(max)=0,
	--Other
	@rUIDNumber nvarchar(50),
	@rBirthdateInWord nvarchar(150),
	@rTransportModeId int,
	@rBloodGroupId tinyint,
	@rBirthPlace nvarchar(150),
    @rBirthTaluka nvarchar(150),
    @rBirthDistrict nvarchar(150),
	@rFamilyCast nvarchar(100),
    @rFamilySubCast nvarchar(100),
    @rCastCategoryId int,
	@rReligionId int,
	@rHouseId int,
    @rMotherTongueId int,
	@rNationalityId int,
	@rHobby nvarchar(50),
	@rReferenceRemark nvarchar(100) = '',
	@rAdhaarNumber nvarchar(20) = '',
	@rMotherTongue nvarchar(100) = '',
	@rQuotaId int =0,
    @rbirthState nvarchar(100)='',
    @rBirthCountry nvarchar(100)='',
	@rBankAccountNumber nvarchar(20),
	@rBankName nvarchar(100),
	@rBankBranch nvarchar(100),
	@rBankIFSCCode nvarchar(20),
	@rClass9BoardRegistrationNumber nvarchar(20),
	@rClass11BoardRegistrationNumber nvarchar(20),
	@rPassportNumber nvarchar(20),
	@rPassportType nvarchar(20),
	@rPassportCountryCode nvarchar(100),
	@rPassportIssueDate date,
	@rPassportExpiryDate date,
	@rBankAccountHolderName nvarchar(200) = '',

	--Family
	@rFatherName	nvarchar(100),
	@rFatherDateOfBirth	date,
	@rFatherOccupation	nvarchar(50),
	@rFatherQualification	nvarchar(50),
	@rFatherContactNo	nvarchar(50),
	@rFatherMail	nvarchar(50),
	@rFatherOfficeAddress	nvarchar(500),
	@rFatherIncome	int,
	@rMotherName	nvarchar(100),
	@rMotherDateOfBirth	date,
	@rMotherOccupation	nvarchar(50),
	@rMotherQualification	nvarchar(50),
	@rMotherContactNo	nvarchar(50),
	@rMotherMail	nvarchar(50),
	@rMotherOfficeAddress	nvarchar(500),
	@rMotherIncome	int,
	@rRelationshipName	nvarchar(100),
	@rRelativeName	nvarchar(100),
	@rRelativeDateOfBirth	date,
	@rRelativeOccupation	nvarchar(50),
	@rRelativeQualification	nvarchar(50),
	@rRelativeContactNo	nvarchar(50),
	@rRelativeMail	nvarchar(50),
	@rRelativeOfficeAddress	nvarchar(500),
	@rRelativeIncome	int,
	@rFatherPhoto varbinary(max)=0,
	@rMotherPhoto varbinary(max)=0,
	@rRelativePhoto varbinary(max)=0,
	@rLiveWithId tinyint=0,
	@rIsFatherExStudent bit=0,
	@rFatherPassOutYear nvarchar(20)='',
	@rIsMotherExStudent bit=0,
	@rMotherPassOutYear nvarchar(20)='',
	@rIsRelativeExStudent bit=0,
	@rRelativePassOutYear nvarchar(20)='',
	@rIsSingleChild bit = 0,
	@rFatherOrganization nvarchar(200),
	@rFatherDesignation nvarchar(100),
	@rMotherOrganization nvarchar(200),
	@rMotherDesignation nvarchar(100),
	@rRelativeOrganization nvarchar(200),
	@rRelativeDesignation nvarchar(100),
	@rFatherAadharNo nvarchar(20)= '',
	@rMotherAadharNo nvarchar(20)= '',
	@rFatherOfficeContactNo nvarchar(50) = '',
	@rMotherOfficeContactNo nvarchar(50) = '',
	--Change for mantis 29443
	@rMarriageAnniversaryDate date, 

	--Communication
	@rPresentStreetOne nvarchar(150),
	@rPresentStreetTwo nvarchar(150),
	@rPresentStreetThree nvarchar(150),
	@rPresentCountry nvarchar(50),
	@rPresentState nvarchar(50),
	@rPresentCity nvarchar(50),
	@rPresentZipCode nvarchar(20),
	@rPresentContactNo nvarchar(20),
	@rPermanentStreetOne nvarchar(150),
	@rPermanentStreetTwo nvarchar(150),
	@rPermanentStreetThree nvarchar(150),
	@rPermanentCountry nvarchar(50),
	@rPermanentState nvarchar(50),
	@rPermanentCity nvarchar(50),
	@rPermanentZipCode nvarchar(20),
	@rPermanentContactNo nvarchar(20),
	@rEmergencyStreetOne nvarchar(150),
	@rEmergencyStreetTwo nvarchar(150),
	@rEmergencyStreetThree nvarchar(150),
	@rEmergencyCountry nvarchar(50),
	@rEmergencyState nvarchar(50),
	@rEmergencyCity nvarchar(50),
	@rEmergencyZipCode nvarchar(20),
	@rEmergencyContactNo nvarchar(20),
	@rParentContactNo nvarchar(20),
	@rParentEmail nvarchar(50),
	@rStudentContactNo nvarchar(50),
	@rStudentEmail nvarchar(50),
	@rPresentDistanceFromSchool decimal(10,2),
	@rStudentCustomAlert nvarchar(1000) = '',
	@rWhatsAppContactNo nvarchar(20) = '',

	--Admission
	@rPreviousSchool nvarchar(200) ,
	@rPreviousSchoolTypeId int,
	@rPreviousStudentId bigint ,
	@rAdmissionFormId bigint ,
	@rAdmissionFormNumber nvarchar(20) ,
	@rAdmissionStandardId int ,
	@rAdmissionDate date ,
	@rAdmissionYear nvarchar(10) ,
	@rLeftStandardId int ,
	@rLeftDate date ,
	@rLeftYear nvarchar(10) ,
	@rInactiveDate date ,
	@rInActiveReason nvarchar(200) ,
	@rLeftReason nvarchar(200) ,
	@rLCProgress nvarchar(200) ,
	@rLCConduct nvarchar(200) ,
	@rLCBook nvarchar(20) ,
	@rLCNumber nvarchar(20) ,
	@rLCDate date ,
	@rLCRemark nvarchar(200) ,
	@rLCCopy tinyint ,
	@rLcId bigint ,
	@rExamSeatNo nvarchar(20) ,
	@rAdmissionNumber nvarchar(50) ,
	@rIsTransfer bit ,
	@rTransferFrom nvarchar(150) ,
	@rPassingYear nvarchar(20) ,
	@rIsTFWS bit ,
	@rIsCertificateHolder bit ,
	@rCertificateName nvarchar(100),
	@rAdmissionQuotaId int ,
	@rPreviousStandard nvarchar (50),
	@rPreviousLCNumber nvarchar (50) ,
	@rPreviousLCDate date,
	@rPreviousLCResult nvarchar (50) ,
	@rProofOfDOB nvarchar (200),

	--CollegeDetail
	--@rAdmissionNumber nvarchar(50),
    --@rIsTransfer bit,
    --@rTransferFrom nvarchar(150),
    --@rPassingYear nvarchar(20),
    --@rIsTFWS bit,
    --@rIsCertificateHolder bit,
    --@rCertificateName nvarchar(100),
    @rSSCBoard nvarchar(200),
    @rSSCSchool nvarchar(200),
    @rSSCPassingYear nvarchar(10),
    @rSSCObtainMarks decimal(10,2),
    @rSSCOutOfMarks decimal(10,2),
    @rSSCPercentage decimal(10,2),
    @rSSCMathMarks decimal(10,2),
    @rSSCMathOutOfMarks decimal(10,2),
    @rHSCBoard nvarchar(200),
    @rHSCSchool nvarchar(200),
    @rHSCPassingYear nvarchar(10),
    @rHSCObtainMarks decimal(10,2),
    @rHSCOutOfMarks decimal(10,2),
    @rHSCPercentage decimal(10,2),
    @rHSCPhysicsMarks decimal(10,2),
    @rHSCPhysicsOutOfMarks decimal(10,2),
    @rHSCChemistryMarks decimal(10,2),
    @rHSCChemistryOutOfMarks decimal(10,2),
    @rHSCMathMarks decimal(10,2),
    @rHSCMathOutOfMarks decimal(10,2),
    @rHSCBiologyMarks decimal(10,2),
    @rHSCBiologyOutOfMarks decimal(10,2),
    @rPCMMarks decimal(10,2),
    @rPCBMarks decimal(10,2),
    @rJEERollNo nvarchar(20),
    @rJEEMeritNo nvarchar(20),
    @rJEEMeritMarks decimal(10,2),
    @rJEEOutOfMarks decimal(10,2),
    @rDiplomaBoard nvarchar(200),
    @rDiplomaCollege nvarchar(200),
    @rDiplomaPassingYear nvarchar(10),
    @rDiplomaObtainMarks decimal(10,2),
    @rDiplomaOutOfMarks decimal(10,2),
    @rDiplomaPercentage decimal(10,2),
    @rApplicationNo nvarchar(20),
    @rAdmissionRound nvarchar(20),
    @rMaritalStatusId tinyint,
    @rSSCPercentile decimal(10,2),
    @rSSCGrade nvarchar(20)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	

	Declare @rNumber bigint
	Select @rNumber = ISNULL(Max(Id),0) + 1 from sStudent.tOnlineRegistrationStudentMaster Where OrgId = @rOrgId

	IF(@rId=0)
	BEGIN		 
	 
					
			IF EXISTS (SELECT Id from sStudent.tOnlineRegistrationStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId)
			BEGIN
				SELECT -100 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
		
			IF(ISNULL(@rUIDNumber,'')!='')		
			  BEGIN
				IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND UIDNumber=@rUIDNumber)
				BEGIN
					SELECT -101 AS Result
					RETURN
				END 
			  END
		 
			IF(ISNULL(@rAdhaarNumber,'')!='')		 		 
			  BEGIN
				IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND  AdhaarNumber=@rAdhaarNumber)
					BEGIN
						SELECT -102 AS Result
						RETURN
					END 
			  END
		--END
	END
	ELSE
	BEGIN
	
		IF EXISTS (SELECT Id from sStudent.tOnlineRegistrationStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		BEGIN
			SELECT -100 AS RESULT, '' AS Code, 0 AS Id 
			RETURN
		END 
	
		IF(ISNULL(@rUIDNumber,'')!='')		
		  BEGIN
			IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND UIDNumber=@rUIDNumber AND StudentId <> @rId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END 
		  END
		  
		 IF(ISNULL(@rAdhaarNumber,'')!='')	
		  BEGIN
			IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND AdhaarNumber=@rAdhaarNumber AND StudentId <> @rId)
				BEGIN
					SELECT -102 AS Result
					RETURN
				END 
		  END
	END

	BEGIN TRY
	
	 BEGIN TRANSACTION	
	IF(@rId=0)
	BEGIN	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tOnlineRegistrationStudentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--PRINT(@lNextNumber)
	IF(@rNumber=0)
	BEGIN
	SET @rNumber=@lNextNumber
	END
	INSERT INTO sStudent.tOnlineRegistrationStudentMaster
		(
			Id,
			Code,
			Number,
			RegistrationNumber,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			--DepartmentId,
			AdmissionCategoryId,
			StatusId,
			RecordStatusId,
			CreatedUserId,
			CreatedDateTime,
			ClassId,
			DivisionId,
			RollNo,
			BatchId,
			StudentStatusId,
			StudentPhoto
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rNumber,
			@rRegistrationNumber,
			@rFirstName,
			@rMiddleName,
			@rLastName,
			@rOrgId,
			--@rDepartmentId,
			@rAdmissionCategoryId,
			@rStatusId,
			@rRecordStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rClassId,
			@rDivisionId,
			@rRollNo,
			@rBatchId,
			@rStudentStatusId,
			@rStudentPhoto
			
		)
		
	INSERT INTO sStudent.tOnlineRegistrationStudentOther
		(
			StudentId,
			UIDNumber,
			DateOfBirth,
			BirthDateInWord,
			TransportModeId,
			GenderId,
			BloodGroupId,
			BirthPlace,
			BirthTaluka,
			BirthDistrict,
			FamilyCast,
			FamilySubCast,
			CastCategoryId,
			ReligionId,
			HouseId,
			MotherTongueId,
			NationalityId,
			Hobby,
			CreatedUserId,
			CreatedDateTime,
			ReferenceRemark,
			AdhaarNumber,
			MotherTongue,
			QuotaId,
			BirthState,
			BirthCountry,
			BankAccountNumber,
			BankName,
			BankBranch,
			BankIFSCCode,
			Class9BoardRegistrationNumber,
			Class11BoardRegistrationNumber,
			PassportNumber,
			PassportType,
			PassportCountryCode,
			PassportIssueDate,
			PassportExpiryDate,
			BankAccountHolderName

		)
		VALUES
		(
			@lNextNumber,
			@rUIDNumber,
			@rDateOfBirth,
			@rBirthDateInWord,
			@rTransportModeId,
			@rGenderId,
			@rBloodGroupId,
			@rBirthPlace,
			@rBirthTaluka,
			@rBirthDistrict,
			@rFamilyCast,
			@rFamilySubCast,
			@rCastCategoryId,
			@rReligionId,
			@rHouseId,
			@rMotherTongueId,
			@rNationalityId,
			@rHobby,
			@rCreatedUserId,
			sCommon.fGetDate(),
		    @rReferenceRemark,
			@rAdhaarNumber,
			@rMotherTongue,
			@rQuotaId,
			@rBirthState,
			@rBirthCountry,
			@rBankAccountNumber,
			@rBankName,
			@rBankBranch,
			@rBankIFSCCode,
			@rClass9BoardRegistrationNumber,
			@rClass11BoardRegistrationNumber,
			@rPassportNumber,
			@rPassportType,
			@rPassportCountryCode,
			@rPassportIssueDate,
			@rPassportExpiryDate,
			@rBankAccountHolderName
		)
	
	INSERT INTO sStudent.tOnlineRegistrationStudentFamily
           (StudentId
           ,FatherName
           ,FatherDateOfBirth
           ,FatherOccupation
           ,FatherQualification
           ,FatherContactNo
           ,FatherMail
           ,FatherOfficeAddress
           ,FatherIncome
           ,MotherName
           ,MotherDateOfBirth
           ,MotherOccupation
           ,MotherQualification
           ,MotherContactNo
           ,MotherMail
           ,MotherOfficeAddress
           ,MotherIncome
           ,RelationshipName
           ,RelativeName
           ,RelativeDateOfBirth
           ,RelativeOccupation
           ,RelativeQualification
           ,RelativeContactNo
           ,RelativeMail
           ,RelativeOfficeAddress
           ,RelativeIncome
           ,CreatedUserId
           ,CreatedDateTime
           ,FatherPhoto
           ,MotherPhoto
           ,RelativePhoto
           ,LiveWithId
           ,IsFatherExStudent
           ,FatherPassOutYear
           ,IsMotherExStudent
           ,MotherPassOutYear
           ,IsRelativeExStudent
           ,RelativePassOutYear
           ,IsSingleChild
           ,FatherOrganization
           ,FatherDesignation
           ,MotherOrganization
           ,MotherDesignation
           ,RelativeOrganization
           ,RelativeDesignation
           ,FatherAdhaarNumber
           ,MotherAdhaarNumber
           ,FatherOfficeContactNo
           ,MotherOfficeContactNo
		   ,MarriageAnniversaryDate --Change for mantis 29443
		   )
     VALUES
			(@lNextNumber,
			@rFatherName,
			@rFatherDateOfBirth,
			@rFatherOccupation,
			@rFatherQualification,
			@rFatherContactNo,
			@rFatherMail,
			@rFatherOfficeAddress,
			@rFatherIncome,
			@rMotherName,
			@rMotherDateOfBirth,
			@rMotherOccupation,
			@rMotherQualification,
			@rMotherContactNo,
			@rMotherMail,
			@rMotherOfficeAddress,
			@rMotherIncome,
			@rRelationshipName,
			@rRelativeName,
			@rRelativeDateOfBirth,
			@rRelativeOccupation,
			@rRelativeQualification,
			@rRelativeContactNo,
			@rRelativeMail,
			@rRelativeOfficeAddress,
			@rRelativeIncome,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rFatherPhoto,
			@rMotherPhoto,
			@rRelativePhoto,			
			@rLiveWithId,
			@rIsFatherExStudent,
			@rFatherPassOutYear,
			@rIsMotherExStudent,
			@rMotherPassOutYear,
			@rIsRelativeExStudent,
			@rRelativePassOutYear,
			@rIsSingleChild,
			@rFatherOrganization,
			@rFatherDesignation,
			@rMotherOrganization,
			@rMotherDesignation,
			@rRelativeOrganization,
			@rRelativeDesignation,
			@rFatherAadharNo,
			@rMotherAadharNo,
			@rFatherOfficeContactNo,
			@rMotherOfficeContactNo,
			@rMarriageAnniversaryDate --Change for mantis 29443
			)	

	INSERT INTO sStudent.tOnlineRegistrationStudentCommunication
		(
			StudentId,
			PresentStreetOne,
			PresentStreetTwo,
			PresentStreetThree,
			PresentCountry,
			PresentState,
			PresentCity,
			PresentZipCode,
			PresentContactNo,
			PermanentStreetOne,
			PermanentStreetTwo,
			PermanentStreetThree,
			PermanentCountry,
			PermanentState,
			PermanentCity,
			PermanentZipCode,
			PermanentContactNo,
			EmergencyStreetOne,
			EmergencyStreetTwo,
			EmergencyStreetThree,
			EmergencyCountry,
			EmergencyState,
			EmergencyCity,
			EmergencyZipCode,
			EmergencyContactNo,
			ParentContactNo,
			ParentEmail,
			StudentContactNo,
			StudentEmail,
			CreatedUserId,
			CreatedDateTime,
			PresentDistanceFromSchool,
			StudentCustomAlert
			--WhatsAppContactNo
		)
	VALUES
		(
			@lNextNumber,
			@rPresentStreetOne,
			@rPresentStreetTwo,
			@rPresentStreetThree,
			@rPresentCountry,
			@rPresentState,
			@rPresentCity,
			@rPresentZipCode,
			@rPresentContactNo,
			@rPermanentStreetOne,
			@rPermanentStreetTwo,
			@rPermanentStreetThree,
			@rPermanentCountry,
			@rPermanentState,
			@rPermanentCity,
			@rPermanentZipCode,
			@rPermanentContactNo,
			@rEmergencyStreetOne,
			@rEmergencyStreetTwo,
			@rEmergencyStreetThree,
			@rEmergencyCountry,
			@rEmergencyState,
			@rEmergencyCity,
			@rEmergencyZipCode,
			@rEmergencyContactNo,
			@rParentContactNo,
			@rParentEmail,
			@rStudentContactNo,
			@rStudentEmail,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rPresentDistanceFromSchool,
			@rStudentCustomAlert
			--@rWhatsAppContactNo
			
		)

	INSERT INTO sStudent.tOnlineRegistrationStudentAdmission
           (
		   StudentId,
           PreviousSchool,
           PreviousSchoolTypeId,
           PreviousStudentId,
           --AdmissionFormId,
           AdmissionFormNumber,
           AdmissionStandardId,
           AdmissionDate,
           AdmissionYear,
           LeftStandardId,
           LeftDate,
           LeftYear,
           InactiveDate,
           InActiveReason,
           LeftReason,
           LCProgress,
           LCConduct,
           LCBook,
           LCNumber,
           LCDate,
           LCRemark,
           LCCopy,
           LcId,
           CreatedUserId,
           CreatedDateTime,
           ExamSeatNo,
           AdmissionNumber,
           IsTransfer,
           TransferFrom,
           PassingYear,
           IsTFWS,
           IsCertificateHolder,
           CertificateName,
           AdmissionQuotaId,
           PreviousStandard,
           PreviousLCNumber,
           PreviousLCDate,
           PreviousLCResult,
           ProofOfDOB
		   )
     VALUES
           (
		   @lNextNumber,
           @rPreviousSchool,
           @rPreviousSchoolTypeId,
           @rPreviousStudentId,
          -- @rAdmissionFormId,
           @rAdmissionFormNumber,
           @rAdmissionStandardId,
           @rAdmissionDate,
           @rAdmissionYear,
           @rLeftStandardId,
           @rLeftDate,
           @rLeftYear,
           @rInactiveDate,
           @rInActiveReason,
           @rLeftReason,
           @rLCProgress,
           @rLCConduct,
           @rLCBook,
           @rLCNumber,
           @rLCDate,
           @rLCRemark,
           @rLCCopy,
           @rLcId,
           @rCreatedUserId,
		   sCommon.fGetDate(),
           @rExamSeatNo,
           @rAdmissionNumber,
           @rIsTransfer,
           @rTransferFrom,
           @rPassingYear,
           @rIsTFWS,
           @rIsCertificateHolder,
           @rCertificateName,
           @rAdmissionQuotaId,
           @rPreviousStandard,
           @rPreviousLCNumber,
           @rPreviousLCDate,
           @rPreviousLCResult,
           @rProofOfDOB
		   )

	INSERT INTO sStudent.tOnlineRegistrationCollegeDetail
           (
		   StudentId,
           --AdmissionNumber,
           --IsTransfer,
           --TransferFrom,
           --PassingYear,
           --IsTFWS,
           --IsCertificateHolder,
           --CertificateName,
           SSCBoard,
           SSCSchool,
           SSCPassingYear,
           SSCObtainMarks,
           SSCOutOfMarks,
           SSCPercentage,
           SSCMathMarks,
           SSCMathOutOfMarks,
           HSCBoard,
           HSCSchool,
           HSCPassingYear,
           HSCObtainMarks,
           HSCOutOfMarks,
           HSCPercentage,
           HSCPhysicsMarks,
           HSCPhysicsOutOfMarks,
           HSCChemistryMarks,
           HSCChemistryOutOfMarks,
           HSCMathMarks,
           HSCMathOutOfMarks,
           HSCBiologyMarks,
           HSCBiologyOutOfMarks,
           PCMMarks,
           PCBMarks,
           JEERollNo,
           JEEMeritNo,
           JEEMeritMarks,
           JEEOutOfMarks,
           DiplomaBoard,
           DiplomaCollege,
           DiplomaPassingYear,
           DiplomaObtainMarks,
           DiplomaOutOfMarks,
           DiplomaPercentage,
           ApplicationNo,
           AdmissionRound,
           MaritalStatusId,
           SSCPercentile,
           SSCGrade
		   )
     VALUES
           (
		   @lNextNumber,
           --@rAdmissionNumber,
           --@rIsTransfer,
           --@rTransferFrom,
           --@rPassingYear,
           --@rIsTFWS,
           --@rIsCertificateHolder,
           --@rCertificateName,
           @rSSCBoard,
           @rSSCSchool,
           @rSSCPassingYear,
           @rSSCObtainMarks,
           @rSSCOutOfMarks,
           @rSSCPercentage,
           @rSSCMathMarks,
           @rSSCMathOutOfMarks,
           @rHSCBoard,
           @rHSCSchool,
           @rHSCPassingYear,
           @rHSCObtainMarks,
           @rHSCOutOfMarks,
           @rHSCPercentage,
           @rHSCPhysicsMarks,
           @rHSCPhysicsOutOfMarks,
           @rHSCChemistryMarks,
           @rHSCChemistryOutOfMarks,
           @rHSCMathMarks,
           @rHSCMathOutOfMarks,
           @rHSCBiologyMarks,
           @rHSCBiologyOutOfMarks,
           @rPCMMarks,
           @rPCBMarks,
           @rJEERollNo,
           @rJEEMeritNo,
           @rJEEMeritMarks,
           @rJEEOutOfMarks,
           @rDiplomaBoard,
           @rDiplomaCollege,
           @rDiplomaPassingYear,
           @rDiplomaObtainMarks,
           @rDiplomaOutOfMarks,
           @rDiplomaPercentage,
           @rApplicationNo,
           @rAdmissionRound,
           @rMaritalStatusId,
           @rSSCPercentile,
           @rSSCGrade
		   )
		      
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
			IF(@rNumber=0)
			BEGIN
			SET  @rNumber=(SELECT ISnull(Number,0) FROM sStudent.tOnlineRegistrationStudentMaster WHERE  Id=@rId)
			IF(@rNumber=0)
			SET @rNumber=@lNextNumber
			END
	    UPDATE  sStudent.tOnlineRegistrationStudentMaster
	    SET
			--Code=@rCode,
			Number=@rNumber,
			RegistrationNumber=@rRegistrationNumber,
			FirstName=@rFirstName,
			MiddleName=@rMiddleName,
			LastName=@rLastName,
			--OrgId=@rOrgId,
			--DepartmentId=@rDepartmentId,
			AdmissionCategoryId=@rAdmissionCategoryId,
			StatusId=@rStatusId,
			RecordStatusId=@rRecordStatusId,
	        UpdatedUserId=@rUpdatedUserId,
	        UpdatedDateTime=sCommon.fGetDate(),
			ClassId=@rClassId,
			DivisionId=@rDivisionId,
			RollNo=@rRollNo,
			BatchId=@rBatchId
			--StudentGroupId=@rStudentGroupId ,
		 --   StudentOtherGroupId=@rStudentOtherGroupId
	      
	      WHERE Id = @rId 
	      
	    UPDATE  sStudent.tOnlineRegistrationStudentOther
		SET
			UIDNumber =@rUIDNumber,
			DateOfBirth=@rDateOfBirth,
			BirthDateInWord=@rBirthDateInWord,
			TransportModeId=@rTransportModeId,
			GenderId=@rGenderId,
			BloodGroupId=@rBloodGroupId,
			BirthPlace=@rBirthPlace,
			BirthTaluka=@rBirthTaluka,
			BirthDistrict=@rBirthDistrict,
			FamilyCast=@rFamilyCast,
			FamilySubCast=@rFamilySubCast,
			CastCategoryId=@rCastCategoryId,
			ReligionId=@rReligionId,
			HouseId=@rHouseId,
			MotherTongueId=@rMotherTongueId,
			NationalityId=@rNationalityId,
			Hobby=@rHobby,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ReferenceRemark=@rReferenceRemark,
			AdhaarNumber=@rAdhaarNumber,
			MotherTongue=@rMotherTongue,
			QuotaId=@rQuotaId,
			BirthState=@rBirthState,
			BirthCountry=@rBirthCountry,
			BankAccountNumber=@rBankAccountNumber,
			BankName=@rBankName,
			BankBranch=@rBankBranch,
			BankIFSCCode=@rBankIFSCCode,
			Class9BoardRegistrationNumber=@rClass9BoardRegistrationNumber,
			Class11BoardRegistrationNumber=@rClass11BoardRegistrationNumber,
			PassportNumber=@rPassportNumber,
			PassportType=@rPassportType,
			PassportCountryCode=@rPassportCountryCode,
			PassportIssueDate=@rPassportIssueDate,
			PassportExpiryDate=@rPassportExpiryDate,
			BankAccountHolderName=@rBankAccountHolderName
	       
	      WHERE StudentId = @rId 
	     
		UPDATE sStudent.tOnlineRegistrationStudentFamily 
	SET
           FatherName=@rFatherName,
           FatherDateOfBirth=@rFatherDateOfBirth,
           FatherOccupation=@rFatherOccupation,
           FatherQualification=@rFatherQualification,
           FatherContactNo=@rFatherContactNo,
           FatherMail=@rFatherMail,
           FatherOfficeAddress=@rFatherOfficeAddress,
           FatherIncome=@rFatherIncome,
           MotherName=@rMotherName,
           MotherDateOfBirth=@rMotherDateOfBirth,
           MotherOccupation=@rMotherOccupation,
           MotherQualification=@rMotherQualification,
           MotherContactNo=@rMotherContactNo,
           MotherMail=@rMotherMail,
           MotherOfficeAddress=@rMotherOfficeAddress,
           MotherIncome=@rMotherIncome,
           RelationshipName=@rRelationshipName,
           RelativeName=@rRelativeName,
           RelativeDateOfBirth=@rRelativeDateOfBirth,
           RelativeOccupation=@rRelativeOccupation,
           RelativeQualification=@rRelativeQualification,
           RelativeContactNo=@rRelativeContactNo,
           RelativeMail=@rRelativeMail,
           RelativeOfficeAddress=@rRelativeOfficeAddress,
           RelativeIncome=@rRelativeIncome,
           UpdatedUserId=@rUpdatedUserId,
           UpdatedDateTime=sCommon.fGetDate(),
           FatherPhoto=@rFatherPhoto,
           MotherPhoto=@rMotherPhoto,
           RelativePhoto=@rRelativePhoto,          
           LiveWithId=@rLiveWithId,
           IsFatherExStudent=@rIsFatherExStudent,
           FatherPassOutYear=@rFatherPassOutYear,
           IsMotherExStudent=@rIsMotherExStudent,
           MotherPassOutYear=@rMotherPassOutYear,
           IsRelativeExStudent=@rIsRelativeExStudent,
           RelativePassOutYear=@rRelativePassOutYear,
           IsSingleChild=@rIsSingleChild,
           FatherOrganization=@rFatherOrganization,
           FatherDesignation=@rFatherDesignation,
           MotherOrganization=@rMotherOrganization,
           MotherDesignation=@rMotherDesignation,
           RelativeOrganization=@rRelativeOrganization,
           RelativeDesignation=@rRelativeDesignation,
           FatherAdhaarNumber=@rFatherAadharNo,
           MotherAdhaarNumber=@rMotherAadharNo,
           FatherOfficeContactNo=@rFatherOfficeContactNo,
           MotherOfficeContactNo=@rMotherOfficeContactNo,
		   MarriageAnniversaryDate=@rMarriageAnniversaryDate --Change for mantis 29443
	      WHERE StudentId = @rId 

		UPDATE  sStudent.tOnlineRegistrationStudentCommunication
	    SET
			
			PresentStreetOne=@rPresentStreetOne, 
			PresentStreetTwo=@rPresentStreetTwo, 
			PresentStreetThree=@rPresentStreetThree,
			PresentCountry=@rPresentCountry,
			PresentState=@rPresentState,
			PresentCity=@rPresentCity,
			PresentZipCode=@rPresentZipCode,
			PresentContactNo=@rPresentContactNo,
			PermanentStreetOne=@rPermanentStreetOne,
			PermanentStreetTwo=@rPermanentStreetTwo,
			PermanentStreetThree=@rPermanentStreetThree,
			PermanentCountry=@rPermanentCountry,
			PermanentState=@rPermanentState,
			PermanentCity=@rPermanentCity,
			PermanentZipCode=@rPermanentZipCode,
			PermanentContactNo=@rPermanentContactNo,
			EmergencyStreetOne=@rEmergencyStreetOne,
			EmergencyStreetTwo=@rEmergencyStreetTwo,
			EmergencyStreetThree=@rEmergencyStreetThree,
			EmergencyCountry=@rEmergencyCountry,
			EmergencyState=@rEmergencyState,
			EmergencyCity=@rEmergencyCity,
			EmergencyZipCode=@rEmergencyZipCode,
			EmergencyContactNo=@rEmergencyContactNo,
			ParentContactNo=@rParentContactNo,
			ParentEmail=@rParentEmail,
			StudentContactNo=@rStudentContactNo,
			StudentEmail=@rStudentEmail,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			PresentDistanceFromSchool=@rPresentDistanceFromSchool,
			StudentCustomAlert = @rStudentCustomAlert,
			WhatsAppContactNo = @rWhatsAppContactNo
	      
	     WHERE StudentId = @rId 	

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

		SET
           --AdmissionNumber = @rAdmissionNumber,
           --IsTransfer = @rIsTransfer,
           --TransferFrom = @rTransferFrom,
           --PassingYear = @rPassingYear,
           --IsTFWS = @rIsTFWS,
           --IsCertificateHolder = @rIsCertificateHolder,
           --CertificateName = @rCertificateName,
           SSCBoard = @rSSCBoard,
           SSCSchool =@rSSCSchool,
           SSCPassingYear =@rSSCPassingYear,
           SSCObtainMarks = @rSSCObtainMarks,
           SSCOutOfMarks = @rSSCOutOfMarks,
           SSCPercentage = @rSSCPercentage,
           SSCMathMarks = @rSSCMathMarks,
           SSCMathOutOfMarks = @rSSCMathOutOfMarks,
           HSCBoard = @rHSCBoard,
           HSCSchool = @rHSCSchool,
           HSCPassingYear = @rHSCPassingYear,
           HSCObtainMarks = @rHSCObtainMarks,
           HSCOutOfMarks = @rHSCOutOfMarks,
           HSCPercentage = @rHSCPercentage,
           HSCPhysicsMarks = @rHSCPhysicsMarks,
           HSCPhysicsOutOfMarks = @rHSCPhysicsOutOfMarks,
           HSCChemistryMarks = @rHSCChemistryMarks,
           HSCChemistryOutOfMarks = @rHSCChemistryOutOfMarks,
           HSCMathMarks = @rHSCMathMarks,
           HSCMathOutOfMarks = @rHSCMathOutOfMarks,
           HSCBiologyMarks = @rHSCBiologyMarks,
           HSCBiologyOutOfMarks = @rHSCBiologyOutOfMarks,
           PCMMarks = @rPCMMarks,
           PCBMarks = @rPCBMarks,
           JEERollNo = @rJEERollNo,
           JEEMeritNo = @rJEEMeritNo,
           JEEMeritMarks = @rJEEMeritMarks,
           JEEOutOfMarks = @rJEEOutOfMarks,
           DiplomaBoard = @rDiplomaBoard,
           DiplomaCollege = @rDiplomaCollege,
           DiplomaPassingYear =@rDiplomaPassingYear,
           DiplomaObtainMarks = @rDiplomaObtainMarks,
           DiplomaOutOfMarks = @rDiplomaOutOfMarks,
           DiplomaPercentage = @rDiplomaPercentage,
           ApplicationNo = @rApplicationNo,
           AdmissionRound = @rAdmissionRound,
           MaritalStatusId = @rMaritalStatusId,
           SSCPercentile = @rSSCPercentile,
           SSCGrade =@rSSCGrade
		   WHERE StudentId = @rId

	 --    IF(@rStatusId=3)
		--BEGIN
		--    UPDATE sSecurity.tUser
		--	   SET IsObsolete=1 
		--	WHERE SourceTypeId=2003 AND SourceId=@rId
		--END
	 END  
	 
		SET @OutStudentId = @lNextNumber
	  SELECT 1 AS Result, @rCode AS Code, @lNextNumber AS Id 
		--SELECT @lNextNumber AS Result
	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sStudent].[pOnlineStudentSearchGet]...';


GO


 
ALTER PROCEDURE [sStudent].[pOnlineStudentSearchGet]
	 
	@rStudentId bigint,
	@rCode nvarchar(20),
	@rFirstName nvarchar(100)='',
	@rMiddleName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rClassId int=0,
	@rDivisionId int=0,
	--@rRollNo int=NULL,
	@rOrgId int,
	@rStatusId smallint=0,
	@rBatchId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
	BEGIN
		SET @rCode= sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rMiddleName = sCommon.fSearchStringGet(@rMiddleName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	END

	SELECT 
			SM.Id AS StudentId,
			SM.Code,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			SM.ClassId,
			SM.DivisionId,
			SM.FirstName +' '+SM.MiddleName +' '+SM.LastName AS Name,
			SM.RollNo,
			(CM.DisplayTitle+'-'+DM.DisplayTitle) AS ClassDivision,
			CM.DisplayTitle AS ClassName,
			DM.DisplayTitle AS DivisionName,
			SM.StudentStatusId,
            SM.OrgId,
			SM.StatusId,
			SM.RecordStatusId,
			SM.AdmissionCategoryId,
			SM.RegistrationNumber,
			SM.BatchId,
			(CASE WHEN SM.StatusId =1 THEN 'Active'
			WHEN SM.StatusId =2 THEN 'InActive'
			WHEN SM.StatusId =2 THEN 'Left' ELSE '' END) AS StatusName,
			SM.StudentPhoto,

			--Other
			SO.UIDNumber,
			ISNULL(SO.DateOfBirth,'0001/01/01')AS DateOfBirth,
			SO.BirthDateInWord,
			SO.TransportModeId,
			SO.GenderId,
			SO.BloodGroupId,
			SO.BirthPlace,
			SO.BirthTaluka,
			SO.BirthDistrict,
			SO.FamilyCast,
			SO.FamilySubCast,
			SO.CastCategoryId,
			SO.ReligionId,
			SO.HouseId,
			SO.MotherTongueId,
			SO.NationalityId,
			SO.Hobby,
			SO.CreatedUserId,
			--SO.CreatedDateTime,
			SO.UpdatedUserId,
			--SO.UpdatedDateTime,
			SO.ReferenceRemark,
			SO.AdhaarNumber,
			SO.MotherTongue,
			SO.QuotaId,
			SO.BirthState,
			SO.BirthCountry,
			SO.BankAccountNumber,
			SO.BankName,
			SO.BankBranch,
			SO.BankIFSCCode,
			SO.Class9BoardRegistrationNumber,
			SO.Class11BoardRegistrationNumber,
			SO.PassportNumber,
			SO.PassportType,
			SO.PassportCountryCode,
			ISNULL(SO.PassportIssueDate,'0001/01/01')AS PassportIssueDate,
			ISNULL(SO.PassportExpiryDate,'0001/01/01')AS PassportExpiryDate,
			SO.BankAccountHolderName,

			--Family

			SF.FatherName,
			ISNULL(SF.FatherDateOfBirth ,'0001/01/01')AS FatherDateOfBirth,
			SF.FatherOccupation,
			SF.FatherQualification,
			SF.FatherContactNo,
			SF.FatherMail,
			SF.FatherOfficeAddress,
			SF.FatherIncome,
			SF.MotherName,
			ISNULL(SF.MotherDateOfBirth ,'0001/01/01')AS MotherDateOfBirth,
			SF.MotherOccupation,
			SF.MotherQualification,
			SF.MotherContactNo,
			SF.MotherMail,
			SF.MotherOfficeAddress,
			SF.MotherIncome,
			SF.RelationshipName,
			SF.RelativeName,
			ISNULL(SF.RelativeDateOfBirth ,'0001/01/01')AS RelativeDateOfBirth,
			SF.RelativeOccupation,
			SF.RelativeQualification,
			SF.RelativeContactNo,
			SF.RelativeMail,
			SF.RelativeOfficeAddress,
			SF.RelativeIncome,
			SF.FatherPhoto,
			SF.MotherPhoto,
			SF.RelativePhoto,			
			SF.LiveWithId,
			SF.IsFatherExStudent,
			SF.FatherPassOutYear,
			SF.IsMotherExStudent,
			SF.MotherPassOutYear,
			SF.IsRelativeExStudent,
			SF.RelativePassOutYear,
			SF.IsSingleChild,
			SF.FatherOrganization,
			SF.FatherDesignation,
			SF.MotherOrganization,
			SF.MotherDesignation,
			SF.RelativeOrganization,
			SF.RelativeDesignation,
			SF.FatherAdhaarNumber,
			SF.MotherAdhaarNumber,
			SF.FatherOfficeContactNo,
			SF.MotherOfficeContactNo,
			ISNULL(SF.MarriageAnniversaryDate ,'0001/01/01')AS MarriageAnniversaryDate, --Change for mantis 29443

			--Admission
			SA.PreviousSchool,
			SA.PreviousSchoolTypeId,
			SA.PreviousStudentId,
			SA.AdmissionFormNumber,
			SA.AdmissionStandardId,
			ISNULL(SA.AdmissionDate ,'0001/01/01')AS AdmissionDate,
			SA.AdmissionYear,
			SA.LeftStandardId,
			ISNULL(SA.LeftDate ,'0001/01/01')AS LeftDate,
			SA.LeftYear,
			ISNULL(SA.InactiveDate ,'0001/01/01')AS InactiveDate,
			SA.InActiveReason,
			SA.LeftReason,
			SA.LCProgress,
			SA.LCConduct,
			SA.LCBook,
			SA.LCNumber,
			ISNULL(SA.LCDate ,'0001/01/01')AS LCDate,
			SA.LCRemark,
			SA.LCCopy,
			SA.LcId,
			SA.ExamSeatNo,
			SA.AdmissionNumber,
			SA.IsTransfer,
			SA.TransferFrom,
			SA.PassingYear,
			SA.IsTFWS,
			SA.IsCertificateHolder,
			SA.CertificateName,
			SA.AdmissionQuotaId,
			SA.PreviousStandard,
			SA.PreviousLCNumber,
			ISNULL(SA.PreviousLCDate ,'0001/01/01')AS PreviousLCDate,
			SA.PreviousLCResult,
			SA.ProofOfDOB,

			--Communication
			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,
			SC.PresentDistanceFromSchool,
			SC.StudentCustomAlert,
			SC.WhatsAppContactNo,

			--College
			SCD.SSCBoard,
			SCD.SSCSchool,
			SCD.SSCPassingYear,
			SCD.SSCObtainMarks,
			SCD.SSCOutOfMarks,
			SCD.SSCPercentage,
			SCD.SSCMathMarks,
			SCD.SSCMathOutOfMarks,
			SCD.HSCBoard,
			SCD.HSCSchool,
			SCD.HSCPassingYear,
			SCD.HSCObtainMarks,
			SCD.HSCOutOfMarks,
			SCD.HSCPercentage,
			SCD.HSCPhysicsMarks,
			SCD.HSCPhysicsOutOfMarks,
			SCD.HSCChemistryMarks,
			SCD.HSCChemistryOutOfMarks,
			SCD.HSCMathMarks,
			SCD.HSCMathOutOfMarks,
			SCD.HSCBiologyMarks,
			SCD.HSCBiologyOutOfMarks,
			SCD.PCMMarks,
			SCD.PCBMarks,
			SCD.JEERollNo,
			SCD.JEEMeritNo,
			SCD.JEEMeritMarks,
			SCD.JEEOutOfMarks,
			SCD.DiplomaBoard,
			SCD.DiplomaCollege,
			SCD.DiplomaPassingYear,
			SCD.DiplomaObtainMarks,
			SCD.DiplomaOutOfMarks,
			SCD.DiplomaPercentage,
			SCD.ApplicationNo,
			SCD.AdmissionRound,
			SCD.MaritalStatusId,
			SCD.SSCPercentile,
			SCD.SSCGrade,

			OM.Title AS OrgName,
			BM.Title AS BatchName,
			StM.Title AS RecordStatus,
			GM.Title AS Gender,
			RM.Title AS Religion,
			BGM.Title AS BloodGroup,
			CCM.Title AS CastCategory,
			HM.Title AS House,
			MT.Title AS MotherTongue,
			CM1.Nationality AS Nationality,
			TM.Title AS Transport,
			QM.Title AS Quota,
			LWM.Title AS LiveWith

			--ACM.Title AS AdmissionCategory,
			--CM.Title AS AdmissionStandard
  FROM 
         sStudent.tOnlineRegistrationStudentMaster SM    
		 INNER JOIN sSetup.tClassMaster CM ON CM.Id=SM.ClassId
	     INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SM.DivisionId  
		 LEFT JOIN sStudent.tOnlineRegistrationStudentOther SO ON SM.Id = SO.StudentId
		 LEFT JOIN sStudent.tOnlineRegistrationStudentFamily SF ON SM.Id = SF.StudentId
		 LEFT JOIN sStudent.tOnlineRegistrationStudentAdmission SA ON SM.Id = SA.StudentId
		 LEFT JOIN sStudent.tOnlineRegistrationStudentCommunication SC ON SM.Id = SC.StudentId
		 LEFT JOIN sStudent.tOnlineRegistrationCollegeDetail SCD on SM.Id = SCD.StudentId
		 INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
		 INNER JOIN sSetup.tBatchMaster BM ON SM.BatchId = BM.Id
		 LEFT JOIN sCommon.tStatusMaster StM ON SM.RecordStatusId = StM.Id
		 LEFT JOIN sCommon.tGenderMaster GM ON SO.GenderId = GM.Id
		 LEFT JOIn sCommon.tReligionMaster RM ON SO.ReligionId = RM.Id
		 LEFT JOIN sCommon.tBloodGroupMaster BGM ON SO.BloodGroupId = BGM.Id
		 LEFT JOIN sCommon.tCastCategoryMaster CCM ON SO.CastCategoryId = CCM.Id
		 LEFT JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
		 LEFT JOIN sCommon.tMotherTongueMaster MT ON SO.MotherTongueId = MT.Id
		 LEFT JOIN sCommon.tCountryMaster CM1 ON SO.NationalityId = CM1.Id 
		 LEFT JOIN sTransport.tTransportMaster TM ON SO.TransportModeId = TM.Id
		 LEFT JOIn sCommon.tQuotaMaster QM ON SO.QuotaId = QM.Id
		 LEFT JOIn sCommon.tLiveWithMaster LWM ON SF.LiveWithId = LWM.Id
		 --LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON SM.AdmissionCategoryId = ACM.Id
		 --LEFT JOIN sStudent.tOnlineRegistrationStudentAdmission SA1 ON CM.Id = SA1.AdmissionStandardId
  WHERE 
		((SM.Id = @rStudentId) OR (@rStudentId = 0))
        AND((SM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SM.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SM.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = '')) 
		AND((SM.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SM.ClassId=@rClassId)OR(@rClassId=0))
		AND((SM.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		--AND(SM.RollNo=@rRollNo)
		AND((SM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SM.OrgId=@rOrgId)
		AND(SM.BatchId=@rBatchId or @rBatchId = 0)
		
ORDER BY SM.RollNo

		
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentVerificationGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentVerificationGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=0,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20) = '',
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rDepartmentId int,
	@rOrgGroupId smallint,
	@rToRollNo int=0,
	@rFromCode nvarchar(20)='',
	@rToCode nvarchar(20)='',
	@rSpecificCode nvarchar(max)=''
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 

	BEGIN
		SET @rCode= sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	END
 
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.ClassId,
			Sa.MiddleName,
			ISNULL(SA.AdmissionDate,'')As AdmissionDate,
			SA.PreviousSchool,
			ISNULL(SA.DateOfBirth,'') As DateOfBirth,
			SA.BirthPlace,
			SA.Gender,
			SA.FamilyCast,
			SA.CastCatagory AS CasteCategory,
			SA.MotherTongue,
			SA.Nationality,
			Sa.FatherName,
			SA.FatherContactNo,
			SA.Mothername,
			SA.MotherContactNo,
			SA.PresentStreetOne,
			SA.PresentStreetTwo,
			SA.PresentStreetThree,
			ISNULL(SA.StudentContactNo,'')As StudentContactNo,
			SA.UIDNumber,
			SA.AdhaarNumber,
			SA.BankBranch,
			SA.BankAccountNumber,
			SA.BankName,
			SA.BankIFSCCode,
			SA.DepartmentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ADMISSIONStandardId, 
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			--SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.Religion,
			SA.StudentEmail,
			SA.Name,
			(select  Title  from sSetup.tClassMaster where OrgId=@rOrgId AND id=SA.ADMISSIONStandardId  ) As AdmissionStandard,
			SA.ClassName,
			SA.BirthState,
			SA.BirthCountry,
			SA.BirthTaluka,
			SA.BirthDistrict,
			SA.BankAccountHolderName,
			ISNULL(SA.MarriageAnniversaryDate,'') AS MarriageAnniversaryDate --Change for mantis 29443
			
  FROM 
            sStudent.vStudentVerification SA  			
  WHERE 
			((SA.ClassId=@rClassId)OR(@rClassId=0))
			AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SA.Code >= @rFromCode) AND (SA.Code <= @rToCode) OR (ISNULL(@rFromCode,'') = '' OR ISNULL(@rToCode,'') = '')) 
			AND(SA.Code IN (SELECT CONVERT(nvarchar,item) from sCommon.fnSplit(@rSpecificCode,',')) OR ISNULL(@rSpecificCode,'') = '') 
			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.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
			and ((sa.RollNO>=@rRollNO)OR(@rRollNo=0))
			and ((sa.RollNO<=@rToRollNo)OR(@rToRollNo=0))
			--AND((SA.Number=@rNumber)OR(@rNumber=0))	

			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo

--ORDER by CASE WHEN @rOrderByTypeId = 1 then SA.FirstName 
--			  WHEN @rOrderByTypeId = 2 then SA.LastName
--			  WHEN @rOrderByTypeId = 4 then (CASE IsNumeric (SA.Code) WHEN 1 THEN Replicate (0, 100 - Len (SA.Code)) + SA.Code  ELSE SA.Code  END) END,		--add
--		CASE WHEN @rOrderByTypeId = 3 then SA.RollNo END,
--		CASE WHEN @rOrderByTypeId = 5 then SA.AdmissionDate END  
--			  ,SA.ClassId, SA.DivisionId,SA.RollNo
 
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentVerificationUpdate]...';


GO

 
 
ALTER PROCEDURE [sStudent].[pStudentVerificationUpdate]
	 
	@rAdmissionDate date='',
	@rPreviousSchool nvarchar(50)='',
	@rStudentId bigint,
	@rDateOfBirth date,
	@rBirthPlace nvarchar(150),
	@rFamilyCast nvarchar(100),
	@rMotherTongue nvarchar(100),
	@rUIDNumber nvarchar(50),
	@rAdhaarNumber nvarchar(20),
	@rFatherContactNo nvarchar(10),
	@rMotherName nvarchar(50),
	@rMotherContactNo nvarchar(10),
	@rStudentContactNo nvarchar(10),
	@rBankBranch nvarchar(100),
	@rBankAccountNumber nvarchar(20),
	@rBankName nvarchar(100),
	@rBankIFSCCode nvarchar(20),
	@rGenderId int,
	@rClassId int=0,
	@rCastCategoryId int,
	@rNationalityId int,
	@rPresentStreetOne nvarchar(300),
	@rPresentStreetTwo nvarchar(300),
	@rPresentStreetThree nvarchar(300),
	@rReligionId int,
	@rFirstName nvarchar(50),
	@rMiddleName nvarchar(50),
	@rLastName nvarchar(50),
	@rStudentEmail nvarchar(50),
	@rAdmissionStandardId int,
	@rFatherName nvarchar(50),
	@rBirthState nvarchar(100),
	@rBirthCountry nvarchar(100),
	@rBirthTaluka nvarchar(100),
	@rBirthDistrict nvarchar(100),
	@rBankAccountHolderName nvarchar (200) = '',
	@rMarriageAnniversaryDate date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 

		IF NOT EXISTS (Select 1 From sStudent.tStudentAdmission Where StudentId=@rStudentId)
		BEGIN
			INSERT INTO sStudent.tStudentAdmission(StudentId) VALUES(@rStudentId)
		END
		
		IF NOT EXISTS (Select 1 From sStudent.tStudentOther Where StudentId=@rStudentId)
		BEGIN
			INSERT INTO sStudent.tStudentOther(StudentId) VALUES(@rStudentId)
		END
		
		IF NOT EXISTS (Select 1 From sStudent.tStudentFamily Where StudentId=@rStudentId)
		BEGIN
			INSERT INTO sStudent.tStudentFamily(StudentId,CreatedUserId,CreatedDateTime) VALUES(@rStudentId,0,sCommon.fGetDate())
		END
		
		IF NOT EXISTS (Select 1 From sStudent.tStudentCommunication Where StudentId=@rStudentId)
		BEGIN
			INSERT INTO sStudent.tStudentCommunication(StudentId,CreatedUserId,CreatedDateTime) VALUES(@rStudentId,0,sCommon.fGetDate())
		END
		
		IF NOT EXISTS (Select 1 From sStudent.tStudentAdditional Where StudentId=@rStudentId)
		BEGIN
			INSERT INTO sStudent.tStudentAdditional(StudentId) VALUES(@rStudentId)
		END
		

	    IF (@rFirstName IS NOT NULL AND @rFirstName != '')
	    BEGIN
		update sStudent.tStudentMaster Set FirstName=@rFirstName Where Id=@rStudentId
		END
		
		IF @rMiddleName IS NOT NULL AND @rMiddleName != ''
		BEGIN
		update sStudent.tStudentMaster Set MiddleName=@rMiddleName Where Id=@rStudentId
		END
		
		IF @rLastName IS NOT NULL AND @rLastName != ''
		BEGIN
		update sStudent.tStudentMaster Set LastName=@rLastName Where Id=@rStudentId
		END
		
		IF @rAdmissionDate IS NOT NULL AND @rAdmissionDate != ''
		BEGIN
		Update sStudent.tStudentAdmission Set AdmissionDate=@rAdmissionDate  Where StudentId =@rStudentId
		END
		
		IF @rPreviousSchool IS NOT NULL AND @rPreviousSchool != ''
		BEGIN
		Update sStudent.tStudentAdmission Set PreviousSchool=@rPreviousSchool  Where StudentId =@rStudentId
		END
		
		IF @rAdmissionStandardId IS NOT NULL AND @rAdmissionStandardId != ''
		BEGIN
		Update sStudent.tStudentAdmission Set AdmissionStandardId=@rAdmissionStandardId Where StudentId =@rStudentId
		END
		
		IF @rDateOfBirth IS NOT NULL AND @rDateOfBirth != ''
		BEGIN
		Update sStudent.tStudentOther Set DateOfBirth=@rDateOfBirth Where StudentId=@rStudentId
		END
		
		IF @rBirthPlace IS NOT NULL AND @rBirthPlace != ''
		BEGIN
		Update sStudent.tStudentOther Set BirthPlace=@rBirthPlace Where StudentId=@rStudentId
		END
		
		IF @rBirthTaluka IS NOT NULL AND @rBirthTaluka != ''
		BEGIN
		Update sStudent.tStudentOther Set BirthTaluka=@rBirthTaluka Where StudentId=@rStudentId
		END
		
		IF @rBirthDistrict IS NOT NULL AND @rBirthDistrict != ''
		BEGIN
		Update sStudent.tStudentOther Set BirthDistrict=@rBirthDistrict Where StudentId=@rStudentId
		END
		
		IF @rFamilyCast IS NOT NULL AND @rFamilyCast != ''
		BEGIN
		Update sStudent.tStudentOther Set FamilyCast=@rFamilyCast Where StudentId=@rStudentId
		END
		 
		IF @rMotherTongue IS NOT NULL AND @rMotherTongue != ''
		BEGIN
		Update sStudent.tStudentOther Set MotherTongue=@rMotherTongue Where StudentId=@rStudentId
		END
		
		IF @rUIDNumber IS NOT NULL AND @rUIDNumber != ''
		BEGIN
		Update sStudent.tStudentOther Set UIDNumber=@rUIDNumber Where StudentId=@rStudentId
		END
		
		IF @rAdhaarNumber IS NOT NULL AND @rAdhaarNumber != ''
		BEGIN
		Update sStudent.tStudentOther Set AdhaarNumber=@rAdhaarNumber Where StudentId=@rStudentId
		END
		
		IF @rGenderId IS NOT NULL AND @rGenderId != ''
		BEGIN
		Update sStudent.tStudentOther Set GenderId=@rGenderId Where StudentId=@rStudentId
		END
		
		IF @rCastCategoryId IS NOT NULL AND @rCastCategoryId != ''
		BEGIN
		Update sStudent.tStudentOther Set CastCategoryId =@rCastCategoryId Where StudentId=@rStudentId
		END
		
		IF @rNationalityId IS NOT NULL AND @rNationalityId != ''
		BEGIN
		Update sStudent.tStudentOther Set NationalityId=@rNationalityId Where StudentId=@rStudentId
		END
		
		IF @rReligionId IS NOT NULL AND @rReligionId != ''
		BEGIN
		Update sStudent.tStudentOther Set ReligionId=@rReligionId Where StudentId=@rStudentId
		END
		
		IF @rBirthState IS NOT NULL AND @rBirthState != ''
		BEGIN
		Update sStudent.tStudentOther Set BirthState = @rBirthState Where StudentId=@rStudentId
		END
		
		IF @rBirthCountry IS NOT NULL AND @rBirthCountry != ''
		BEGIN
		Update sStudent.tStudentOther Set BirthCountry =@rBirthCountry Where StudentId=@rStudentId
		END
		
		IF @rFatherContactNo IS NOT NULL AND @rFatherContactNo != ''
		BEGIN
		Update sStudent.tStudentFamily Set FatherContactNo =@rFatherContactNo Where StudentId=@rStudentId
		END
		
		IF @rMotherName IS NOT NULL AND @rMotherName != ''
		BEGIN
		Update sStudent.tStudentFamily Set MotherName =@rMotherName Where StudentId=@rStudentId
		END
		
		IF @rMotherContactNo IS NOT NULL AND @rMotherContactNo != ''
		BEGIN
		Update sStudent.tStudentFamily Set MotherContactNo =@rMotherContactNo Where StudentId=@rStudentId
		END
		
		IF @rFatherName IS NOT NULL AND @rFatherName != ''
		BEGIN
		Update sStudent.tStudentFamily Set FatherName =@rFatherName Where StudentId=@rStudentId
		END
		
		IF @rStudentContactNo IS NOT NULL AND @rStudentContactNo != ''
		BEGIN
		Update sStudent.tStudentCommunication Set StudentContactNo =@rStudentContactNo Where StudentId=@rStudentId
		END
		
		IF @rPresentStreetOne IS NOT NULL AND @rPresentStreetOne != ''
		BEGIN
		Update sStudent.tStudentCommunication Set PresentStreetOne =@rPresentStreetOne Where StudentId=@rStudentId
		END
		
		IF @rPresentStreetTwo IS NOT NULL AND @rPresentStreetTwo != ''
		BEGIN
		Update sStudent.tStudentCommunication Set PresentStreetTwo =@rPresentStreetTwo Where StudentId=@rStudentId
		END
		
		IF @rPresentStreetThree IS NOT NULL AND @rPresentStreetThree != ''
		BEGIN
		Update sStudent.tStudentCommunication Set PresentStreetThree =@rPresentStreetThree Where StudentId=@rStudentId
		END
		
		IF @rStudentEmail IS NOT NULL AND @rStudentEmail != ''
		BEGIN
		Update sStudent.tStudentCommunication Set StudentEmail =@rStudentEmail Where StudentId=@rStudentId
		END
		
		IF @rBankBranch IS NOT NULL AND @rBankBranch != ''
		BEGIN
		Update sStudent.tStudentAdditional Set BankBranch =@rBankBranch Where StudentId=@rStudentId
		END
		
		IF (@rBankAccountNumber IS NOT NULL AND @rBankAccountNumber != '')
		BEGIN
		Update sStudent.tStudentAdditional Set BankAccountNumber =@rBankAccountNumber Where StudentId=@rStudentId
		END
		
		IF (@rBankName IS NOT NULL AND @rBankName != '')
		BEGIN
		Update sStudent.tStudentAdditional Set BankName =@rBankName Where StudentId=@rStudentId
		END
		
		IF (@rBankIFSCCode IS NOT NULL AND @rBankIFSCCode != '')
		BEGIN
		Update sStudent.tStudentAdditional Set BankIFSCCode =@rBankIFSCCode Where StudentId=@rStudentId
		END

		IF (@rBankAccountHolderName IS NOT NULL AND @rBankAccountHolderName != '')
		BEGIN
		Update sStudent.tStudentAdditional Set BankAccountHolderName =@rBankAccountHolderName Where StudentId=@rStudentId
		END

		/************Change for mantis : 29443************/
		IF (@rMarriageAnniversaryDate IS NOT NULL AND @rMarriageAnniversaryDate != '')
		BEGIN
		Update sStudent.tstudentfamily Set MarriageAnniversaryDate =@rMarriageAnniversaryDate Where StudentId=@rStudentId
		END
		
END
GO
PRINT N'Altering Procedure [sTool].[pDeleteStaticData]...';


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

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


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

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

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

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


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

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

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

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

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

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

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

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

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

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

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

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

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

DELETE FROM sSystem.tStaticVersion

DELETE FROM sCommunication.tFeedBackAnswerGroupMaster

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

DELETE FROM sSystem.tTimeZone
DELETE FROM sTool.tTestCaseTypeMaster

DELETE FROM sAlumni.tEmployeementType

DELETE FROM sErp.tCampusTypeMaster

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

DELETE FROM sSecurity.tScreenHelp
DELETE FROM sSystem.tSettingInfo

DELETE FROM sProcurement.tOtherLocationSourceTypeMaster

DELETE FROM sCommon.tFieldTypeMaster
DELETE FROM sErp.tLeadInfrastructureMaster

DELETE FROM sHostel.tHostelEventMainTypeMaster

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

DELETE FROM sAcademic.tHomeworkCheckStatusMaster
DELETE FROM sAssessment.tExamTypeMaster

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

DELETE FROM sAudit.tOperationMaster

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

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


DELETE FROM sErp.tPlugInMaster
DELETE FROM sErp.tTagMaster

DELETE FROM sErp.tIssueTypeMaster

DELETE FROM sErp.tScreenFunctionalityMaster

DELETE FROM sHrm.tChangeTypeMaster


DELETE FROM sCommon.tDataMaster
DELETE FROM sCommon.tDataTypeMaster

DELETE FROM siTax.tStaticIncomeTaxSubSubGroup

DELETE FROM sCommunication.tStudentDocumentTypeMaster

DELETE FROM sCommon.tUploadFunctionalityMaster
DELETE FROM sCommunication.tEmployeeDocumentTypeMaster

DELETE FROM sErp.tCustomerMessageTypeMaster

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

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

DELETE FROM sSetup.tFormTypeMaster
DELETE FROM sSetup.tFormButtonMaster

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

DELETE FROM sPurchase.tPurchaseReportTemplateMaster
DELETE FROM sWf.tWfStatusMaster
DELETE FROM sWf.tWfFunctionalityMaster
DELETE FROM sWf.tWfTypeMaster

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


GO

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

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

	IF Exists(Select SFM.Id from [sWf].[tWfFunctionalityMaster] SFM
		Inner Join [sWf].[tWfSetup] WFS on WFS.WfFunctionalityId = SFM.Id
		Where WFS.WfTypeMasterId = 2 AND SFM.Id = @rWfFunctionalityId AND @rIsSequancial <> 2)
	BEGIN
		Select @rIsSequancial = case when WfTypeMasterId = 2 then 1 else 0 end,@rWfLevel = WFS.WfLevel from [sWf].[tWfFunctionalityMaster] SFM
		Inner Join [sWf].[tWfSetup] WFS on WFS.WfFunctionalityId = SFM.Id
		Where WFS.WfTypeMasterId = 2 AND WfLevel > 0 AND SFM.Id = @rWfFunctionalityId
	END

	Declare @StatusId smallint
	set @StatusId = @rActionStatusId

	IF(@rIsSequancial = 1)
	BEGIN
		--select @rActionEmployeeId = U.SourceId from   sSecurity.tUser U where U.Id = @rActionEmployeeId

		IF(@rActionStatusId <> 4)
		BEGIN
			DECLARE @LogCount int
			SELECT @LogCount = COUNT(AutoId) FROM [sWf].[tWfHierarchyLevel] WHERE WfApprovalActionId = @rId

			IF(@rWfLevel <> @LogCount)
			Begin
				IF(@rActionStatusId = 3)
				Begin
					set @StatusId = 2
				End
			End

			Declare @HierarchyLevelId bigint
			select @HierarchyLevelId=ISNULL(AutoId,0) from [sWf].[tWfHierarchyLevel] WHERE WfApprovalActionId =@rId AND ActionByEmployeeId=@rActionEmployeeId AND StatusId <> 4
			IF(@HierarchyLevelId > 0)
			Begin
				UPDATE [sWf].[tWfHierarchyLevel] SET StatusId = @StatusId , Remark = @rActionRemark 
				WHERE AutoId = @HierarchyLevelId
			End
			
			SELECT @lActionByEmployeeId = EmployeeManagerId FROM [sHrm].[tEmployeeJobDetail] WHERE EmployeeId = @rActionStatusId
					AND @rActionStatusId IS NOT NULL
			
		END
	END

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

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

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

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

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

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

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

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


GO


--exec [sWf].[pWfApprovalGet] 0,'2023-12-20','2023-12-27',0,9911,'',9911000000270,0
 
ALTER  PROCEDURE [sWf].[pWfApprovalGet]
			 @rWfFunctionalityId smallint=0,
			 @rFromDate date=null,
			 @rToDate date=null,
			 @rStatusId smallint=0,
			 @rOrgId smallint=0,
			 @rCode nvarchar(20) ='',
			 @rUserId bigint ,
			 @rApprovalRequestId bigint = 0

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

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

	UNION

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

	UNION

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

	UNION
		SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PR.Id AS ApprovalRequestId,
		CONVERT(DATE,PR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseRequest PR
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PR.Id AND AA.WfFunctionalityId = 1 AND AA.DocSourceTypeId = 2040
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = 1
	INNER JOIN [sWf].[tWfSetup] SP ON SP.WfFunctionalityId = WFM.Id AND SP.WfTypeMasterId = 3
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE SP.WfTypeMasterId = 3

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

	UNION

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

	UNION

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

	UNION

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

	UNION

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

	UNION

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

	UNION

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

	UNION

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

	UNION

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

	UNION

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

	UNION

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

	UNION

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

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		SR.Id AS ApprovalRequestId,
		CONVERT(DATE,SR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tSalesReturn SR
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = SR.Id AND AA.WfFunctionalityId = 5 AND AA.DocSourceTypeId = 2044
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = 5
	INNER JOIN [sWf].[tWfSetup] SP ON SP.WfFunctionalityId = WFM.Id AND SP.WfTypeMasterId = 3
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE SP.WfTypeMasterId = 3
END
GO
PRINT N'Altering Procedure [sWf].[pWfSetupAdd]...';


GO


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

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

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

				SELECT @rId
			END
			ELSE
			BEGIN
				if not exists(SELECT AA.Id FROM [sWf].[tWfSetup] WS
							Inner Join [sWf].[tWfApprovalAction] AA on WS.WfFunctionalityId = AA.WfFunctionalityId
							WHERE WS.WfFunctionalityId= @rWfFunctionalityId AND WS.WfTypeMasterId <> @rWfTypeMasterId AND AA.ActionStatusId not in (3,4))
				BEGIN
					UPDATE [sWf].[tWfSetup]
					SET 
						WfTypeMasterId = @rWfTypeMasterId,
						WfLevel = @rWfLevel,
						OrgGroupId = @rOrgGroupId,
						WfFunctionalityId = @rWfFunctionalityId
					WHERE AutoId =@rId

					DELETE FROM sWf.tWfApprovingAuthority
					WHERE WfFunctionalityId = @rWfFunctionalityId

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

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


GO
ALTER PROCEDURE [sWorkflow].[pPopUpStatusGet]
			 @rCode nvarchar(50) =0,
			 @rStatusId int=0,
			 @rParticipantSourceId bigint = 0
			 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
			SELECT 

			ADM.Title AS DepartmentTitle,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.CreatedDateTime AS CreatedDateTime,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status,
			ISNULL(AA.ActionRemark, '') AS ActionRemark
			--(select Title from sWorkflow.tActionStatusMaster WHERE Id=3) AS Status 
			--CASE WHEN @rStatusId= 0 THEN (select Top 1 Title from sWorkflow.tActionStatusMaster WHERE Id=3) WHEN ASM.Id = @rStatusId THEN ASM.Title  END AS Status
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
			INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
			INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId
			LEFT JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
		WHERE  (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode ='')))
		AND((ASM.Id = @rStatusId) OR (@rStatusId =0)) 
		AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
		AND ISNULL(EM.IsOtherUser,0) = 0

		UNION 

		SELECT 

			ADM.Title AS DepartmentTitle,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.CreatedDateTime AS CreatedDateTime,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status,
			ISNULL(AA.ActionRemark, '') AS ActionRemark
			--(select Title from sWorkflow.tActionStatusMaster WHERE Id=3) AS Status 
			--CASE WHEN @rStatusId= 0 THEN (select Top 1 Title from sWorkflow.tActionStatusMaster WHERE Id=3) WHEN ASM.Id = @rStatusId THEN ASM.Title  END AS Status
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
			INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
			INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId
			LEFT JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
		WHERE  (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode ='')))
		AND((ASM.Id = @rStatusId) OR (@rStatusId =0)) 
		AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
		AND ISNULL(EM.IsOtherUser,0) = 0
	END
GO
PRINT N'Creating Procedure [sErp].[pVersionUpdate]...';


GO

CREATE PROCEDURE [sErp].[pVersionUpdate]
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 
DECLARE @lCurrentVersionId int , @lReleaseDate Date
SELECT @lCurrentVersionId = VersionId FROM sSystem.tDatabaseInfo

--concat 20 for fullYear (like replace 23 to 2023)
DECLARE @lVersionId int = CONVERT(nvarchar,20)+CONVERT(nvarchar,@lCurrentVersionId)

SELECT @lReleaseDate = ReleaseDate FROM SapphireERP.sErp.tReleaseNote WHERE VersionId = @lVersionId
SELECT 
	Id,
	ReleaseDate,
	VersionNumber,
	VersionId

FROM SapphireERP.sErp.tReleaseNote WHERE ReleaseDate > @lReleaseDate AND IsObsolete = 0  Order By ReleaseDate


--Select * from [sSystem].[tVersionUpdate]
	 
END
GO
PRINT N'Creating Procedure [sPurchase].[pGoodsReceivedNoteApprovedGet]...';


GO

--exec [sPurchase].[pGoodsReceivedNoteApprovedGet] 991100002
CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteApprovedGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  GRN.Id,
				GRN.GRNNumber                               ,
				GRN.OrgGroupId,
				GRN.LocationId,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.VendorId,
				GRN.RequestedBy,
				ISNULL(GRN.BillToAddress, PO.BillToAddress) AS BillToAddress,
				GRN.StatusId,
				GRN.PODueDate,
				ISNULL(SM.Title,'') AS Status,
				VM.Title AS VendorName,
			    PR.Number As PurchaseRequestNumber,
				ISNULL(PO.ShipToAddress,'') AS ShipToAddress,
			    PO.RefNumber AS PurchaseOrderNumber  
		from   [sPurchase].[tGoodsReceivedNote] GRN(nolock) 
			   Left JOIN sProcurement.tVendorMaster  VM on GRN.VendorId = VM.ID
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = GRN.StatusId
			   Left Join [sPurchase].[tPurchaseRequest] PR ON PR.ID = GRN.PurchaseRequestId
			   Left Join [sPurchase].[tPurchaseOrder] PO On PO.Id = GRN.PurchaseOrderId
		where  GRN.Id=@rId AND GRN.IsObsolete = 0 AND GRN.StatusId = 3

		select GRND.Id,
			   GRND.GoodsReceivedNoteId,
			   GRND.PurchaseOrderDetailId,
			   GRND.OrgGroupId,
			   SUMa.Id AS UnitTypeId,
			   GRND.StockItemId,
			   GRND.POQty,
			   GRND.ReceivedQty 
			   - (SELECT ISNULL(Sum(QCD.AcceptedQty + QCD.RejectedQty), 0) AS AdjustedReceivedQty
				FROM [sPurchase].[tGoodsReceivedNote] GRN
					 INNER JOIN [sPurchase].[tGoodsReceivedNoteDetail] GRND1 ON GRND1.[GoodsReceivedNoteId] = GRN.Id
					 LEFT JOIN [sPurchase].[tQualityCheckDetail] QCD ON QCD.[GoodsReceivedNoteDetailId] = GRND1.Id
				where GRND1.[GoodsReceivedNoteId] = GRN.Id AND GRND1.Id = GRND.Id
				GROUP BY GRND1.[GoodsReceivedNoteId]
				HAVING Sum(GRND1.ReceivedQty) > ISNULL(Sum(QCD.AcceptedQty + QCD.RejectedQty), 0)) as ReceivedQty,
			   GRND.PreviousGRNQty,
			   GRND.UnitPrice,
			   GRND.Remark, 
			   SIM.Code	AS StockItemCode,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM,
			   SCM.Id as CategoryId,
			   SCM.Title as CategoryName,
			   0 as SubCategoryId
		from   [sPurchase].[tGoodsReceivedNoteDetail] GRND (nolock)
			   Inner JOIN	sPurchase.tGoodsReceivedNote GRN	ON GRN.Id = GRND.GoodsReceivedNoteId AND GRN.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
		where  GRND.GoodsReceivedNoteId=@rId AND GRN.StatusId = 3 AND GRND.ReceivedQty > 0
	END TRY

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


GO

--exec [sPurchase].[pGoodsReceivedNoteApprovedSearchGet] null,991100001,null,9911,'2023-01-01','2023-12-30',1,10,null
CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteApprovedSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar = '',
	@rOrgGroupId int,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
	@rPageNo int,
	@rPageSize int,
	@rStatusId smallint = null

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


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



		WHERE 
				((GRN.GRNNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND GRN.IsObsolete = 0 AND GRN.StatusId = 3
				AND GRN.Id Not in
				(SELECT GRN8.GoodsReceivedNoteId
				  FROM [sPurchase].[tGoodsReceivedNoteDetail] GRN8
				  Where GRN8.GoodsReceivedNoteId = GRN.Id 
				  And  GRN8.ReceivedQty <=
				 (
				  SELECT ISNULL(Sum(QCD.AcceptedQty),0)+ISNULL(Sum(QCD.RejectedQty),0)
				  FROM [sPurchase].[tQualityCheckDetail] QCD
				  Inner JOIN [sPurchase].[tQualityCheck] QC on QCD.QualityCheckId = Qc.Id
				  where  QC.GoodsReceivedNoteId = GRN8.GoodsReceivedNoteId	AND QCD.GoodsReceivedNoteDetailId =GRN8.Id
				  Group By QC.GoodsReceivedNoteId) 
				  )
				AND ((Cast(GRN.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(GRN.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))

	    Select t.* From (
			Select ROW_NUMBER() Over (
			Order by GRN.Id desc  
			) AS 'RowNum',GRN.Id,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.VendorId,
				GRN.GRNNumber as Number,
				GRN.RequestedBy, 
				GRN.LocationId, 
				GRN.PODueDate,
				ISNULL(SM.Title,'') as Status,
				VM.Code AS VendorCode,
			    VM.Title AS VendorName,
				PR.Number as PurchaseNumber,
				PO.RefNumber as PurchaseOrderNumber

	    FROM		
				sPurchase.tGoodsReceivedNote GRN (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on GRN.StatusId = SM.Id
				Left JOIN sProcurement.tVendorMaster  VM on GRN.VendorId = VM.ID
				Left Join [sPurchase].[tPurchaseRequest] PR on PR.Id = GRN.PurchaseRequestId
				Left Join [sPurchase].[tPurchaseOrder] PO on PO.Id = GRN.PurchaseOrderId
		WHERE 
				((GRN.GRNNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND GRN.IsObsolete = 0 AND GRN.StatusId = 3
				AND GRN.Id Not in
				(SELECT GRN8.GoodsReceivedNoteId
				  FROM [sPurchase].[tGoodsReceivedNoteDetail] GRN8
				  Where GRN8.GoodsReceivedNoteId = GRN.Id 
				  And  GRN8.ReceivedQty <=
				 (
				  SELECT ISNULL(Sum(QCD.AcceptedQty),0)+ISNULL(Sum(QCD.RejectedQty),0)
				  FROM [sPurchase].[tQualityCheckDetail] QCD
				  Inner JOIN [sPurchase].[tQualityCheck] QC on QCD.QualityCheckId = Qc.Id
				  where  QC.GoodsReceivedNoteId = GRN8.GoodsReceivedNoteId	AND QCD.GoodsReceivedNoteDetailId =GRN8.Id
				  Group By QC.GoodsReceivedNoteId) 
				  )
				AND ((Cast(GRN.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(GRN.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
					)t Where t.RowNum Between
		((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

		SELECT @TotalRecords as TotalRecords

	 END TRY

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


GO
CREATE PROCEDURE [sSecurity].[pVerifyEmailIdForEmployeeOTP]

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

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

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

	END

	ELSE
	BEGIN 
		SELECT -102 AS Result,'EmailId is wrong' AS [Message],'' AS OTP, 0 AS UserId
	END
END
GO
PRINT N'Creating Procedure [sStudent].[pGetUploadBulkPhotoData]...';


GO


CREATE PROCEDURE [sStudent].[pGetUploadBulkPhotoData]
@rSourceTypeId int,
@rPageIndex int
 AS

 SET NOCOUNT ON
 BEGIN

	DECLARE @lPageSize int = 20	

	IF OBJECT_ID('tempdb..#tUploadBulkPhotoData') IS NOT NULL DROP TABLE #tUploadBulkPhotoData
	CREATE TABLE #tUploadBulkPhotoData
	(
		Id bigint identity,	
		SourceId Bigint,
		Code nvarchar(20),
		Name nvarchar(300),
		RollNo Int,
		Photo varbinary(max)
	)

	IF(@rSourceTypeId = 2003)

	BEGIN

	INSERT INTO #tUploadBulkPhotoData
	SELECT 
			SM.Id AS SourceId,
			SM.Code,
			(FirstName +' '+ MiddleName +' '+ LastName) AS Name, 
			SA.RollNo,
			SI.StudentPhoto AS Photo
			FROM [sStudent].[tStudentMaster] SM 
			
			INNER JOIN sStudent.tAcademic SA ON SM.Id=SA.StudentId 
			INNER Join sSetup.tBatchMaster BM ON SA.BatchId=BM.Id AND BM.IsActive=1 
			INNER JOIN [sSetup].[tDivisionMaster] AS DM ON DM.Id = SA.DivisionId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id			
			WHERE SA.DivisionId=DM.Id AND SM.StatusId = 1 

	END

	ELSE

		BEGIN
		INSERT INTO #tUploadBulkPhotoData
			SELECT 
			EM.Id AS SourceId,
			EM.Code,
			(FirstName +' '+ MiddleName +' '+ LastName) AS Name, 
			'' AS RollNo,
			EI.EmployeePhoto AS Photo  
			FROM sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId=EM.Id 
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EM.Id 
			INNER JOIN [sSetup].[tDivisionMaster] AS DM ON DM.Id = EJ.OrganizationDepartmentId
			WHERE EJ.OrganizationDepartmentId=DM.Id AND  ISNULL(EM.IsOtherUser,0) = 0 AND EM.StatusId = 7
		END
		Declare @lCount int = (Select Count(Id) from #tUploadBulkPhotoData)

		select Id,Code,Name,Photo,@lCount As TotalRecords
		from #tUploadBulkPhotoData 
		where Id between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)
		
		drop table #tUploadBulkPhotoData
	END
GO
PRINT N'Altering Procedure [sPurchase].[pGoodsReceivedNoteAdd]...';


GO


ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteAdd]
		@rId bigint,
		@rPurchaseRequestId bigint,
		@rPurchaseOrderId bigint,
		@rVendorId int,
		@rPODueDate datetime,	
		@rRequestedBy nvarchar(100),
		@rOrgGroupId smallint,
		@rLocationId int,
		@rStatusId smallint,	
		@rBillToAddress nvarchar(1000),
		@rUserId bigint,
		@rDetailList sPurchase.GoodsReceivedNoteDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			if not exists(select Id from @rDetailList where PreviousGRNQty+ReceivedQty > POQty)
			Begin
				Update sPurchase.tGoodsReceivedNote
				set 
					StatusId = @rStatusId,
					PurchaseRequestId = @rPurchaseRequestId,
					PurchaseOrderId = @rPurchaseOrderId,
					VendorId = @rVendorId,
					PODueDate = @rPODueDate,
					RequestedBy = @rRequestedBy,
					BillToAddress = @rBillToAddress,
					UpdatedUserId = @rUserId,		
					UpdatedDateTime = GetUtcDate()
				where Id = @rId and IsObsolete = 0

				delete from sPurchase.tGoodsReceivedNoteDetail
				where Id not in(select Id from @rDetailList)
				and GoodsReceivedNoteId = @rId

				update sPurchase.tGoodsReceivedNoteDetail
				set
				OrgGroupId = @rOrgGroupId,
				GoodsReceivedNoteId = @rId,
				PurchaseOrderDetailId = DL.PurchaseOrderDetailId,
				StockItemId = DL.StockItemId,
				POQty = DL.POQty,
				ReceivedQty = DL.ReceivedQty,
				PreviousGRNQty = DL.PreviousGRNQty,
				UnitPrice = DL.UnitPrice,
				Remark = DL.Remark,
				UpdatedUserId = @rUserId,
				UpdatedDateTime = GETUTCDATE()
				from @rDetailList DL
				inner join sPurchase.tGoodsReceivedNoteDetail GRN ON DL.ID = GRN.Id
				where GoodsReceivedNoteId = @rId

				DECLARE @lNextNumberGRN BIGINT	 
				EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNoteDetail',@lNextNumber = @lNextNumberGRN output
				set @lNextNumberGRN=@lNextNumberGRN-1
				INSERT INTO sPurchase.tGoodsReceivedNoteDetail
				(
					Id,
					OrgGroupId,
					GoodsReceivedNoteId,
					PurchaseOrderDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					PreviousGRNQty,
					UnitPrice,
					Remark,
					CreatedUserId,
					CreatedDateTime
				)
				select	@lNextNumberGRN+Id,
						@rOrgGroupId,
						@rId,
						PurchaseOrderDetailId,
						StockItemId,
						POQty,
						ReceivedQty,
						PreviousGRNQty,
						UnitPrice,
						Remark,
						@rUserId, 
						GETUTCDATE() 
				from @rDetailList
				where Id not in(Select DL.Id from @rDetailList DL
				inner join sPurchase.tGoodsReceivedNoteDetail GRN ON DL.ID = GRN.Id
				where GRN.GoodsReceivedNoteId = @rId)

				set @lNextNumberGRN=@lNextNumberGRN+(select Count(Id) from @rDetailList where Id not in(Select DL.Id              from @rDetailList DL
				inner join sPurchase.tGoodsReceivedNoteDetail GRN ON DL.ID = GRN.Id
				where GRN.GoodsReceivedNoteId = @rId))
				EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tGoodsReceivedNoteDetail', @rCurrentNumber = @lNextNumberGRN

				Select @rId
			End
			Select -101
		End
		Else
		Begin
		    If Not Exists(select GRN.Id
			from [sPurchase].[tGoodsReceivedNote] GRN(nolock) 
			Inner Join [sWf].[tWfSetup] WFS on GRN.[OrgGroupId] = WFS.[OrgGroupId]
			Where WFS.[WfFunctionalityId] = 4)
			Begin
				Select -102
			End
			if not exists(select Id from @rDetailList where PreviousGRNQty+ReceivedQty > POQty)
			Begin
				DECLARE @lNextNumber INT	 
				EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNote',@lNextNumber = @lNextNumber output	
				--------------select @lNextNumber
				--DECLARE @loNextNumber nVarchar(20)
				--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
				--------------@rNextNumber = @loNextNumber OUTPUT

	 			INSERT INTO sPurchase.tGoodsReceivedNote
				(
					Id,
					GRNNumber,
					PurchaseRequestId,
					PurchaseOrderId,
					PODueDate,
					RequestedBy, 
					OrgGroupId,
					LocationId, 			 
					StatusId,
					VendorId,
					BillToAddress,
					CreatedUserId,		
					CreatedDateTime
	
				)
				VALUES
				(
					@lNextNumber,
					@lNextNumber,
					@rPurchaseRequestId,
					@rPurchaseOrderId,
					@rPODueDate,
					@rRequestedBy,	 
					@rOrgGroupId,
					@rLocationId, 		 
					@rStatusId,
					@rVendorId,
					@rBillToAddress,
					@rUserId,		
					GETUTCDATE()
				)
 
				set @rId = @lNextNumber  
			
				DECLARE @lNextNumberGRND BIGINT	 
				EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNoteDetail',@lNextNumber = @lNextNumberGRND output	
				set @lNextNumberGRND=@lNextNumberGRND-1

	 			INSERT INTO sPurchase.tGoodsReceivedNoteDetail
				(
					Id,
					OrgGroupId,
					GoodsReceivedNoteId,
					PurchaseOrderDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					PreviousGRNQty,
					UnitPrice,
					Remark,
					CreatedUserId,
					CreatedDateTime
				)
				select	@lNextNumberGRND+Id,
						@rOrgGroupId,
						@rId,
						PurchaseOrderDetailId,
						StockItemId,
						POQty,
						ReceivedQty,
						PreviousGRNQty,
						UnitPrice,
						Remark,
						@rUserId, 
						GETUTCDATE() 
				from @rDetailList
						
				set @lNextNumberGRND=@lNextNumberGRND+(select Count(Id) from @rDetailList)
				EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tGoodsReceivedNoteDetail', @rCurrentNumber = @lNextNumberGRND

				select @rId

				Declare @typeId smallint=0
				Declare @Level smallint=0
				Declare @rActionEmployeeId bigint=0
				SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 4
				IF(@typeId = 1)
				BEGIN
					exec [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,1,'',0,0,4,@rOrgGroupId
				END
				ELSE IF(@typeId = 2)
				Begin
					SELECT @rActionEmployeeId = U.SourceId FROM sSecurity.tUser U WHERE U.Id = @rUserId
					exec [sWf].[pWfApprovalAdd] 0,@rId,2043,@rActionEmployeeId,1,'',1,@Level,4,@rOrgGroupId
				End
				ELSE IF(@typeId = 3)
				BEGIN
					exec [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,3,'',0,0,4,@rOrgGroupId
				END
			END
			select -101;
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

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

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

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

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


GO

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

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

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

			delete from sPurchase.tPurchaseOrderDetail
			where Id not in(select Id from @rDetailList)
			and PurchaseOrderId = @rId

			update sPurchase.tPurchaseOrderDetail
			set
			OrgGroupId = @rOrgGroupId,
			PurchaseOrderId = @rId,
			PurchaseRequestDetailId = DL.PurchaseRequestDetailId,
			StockItemId = DL.StockItemId,
			TotalQty = DL.TotalQty,
			Remark = DL.Remark,
			UpdatedUserId = @rUserId,
			UpdatedDateTime = GETUTCDATE()
			from @rDetailList DL
			inner join sPurchase.tPurchaseOrderDetail PO ON DL.ID = PO.Id
			where PurchaseOrderId = @rId

			DECLARE @lNextNumberPOD BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseOrderDetail',@lNextNumber = @lNextNumberPOD output
			set @lNextNumberPOD=@lNextNumberPOD-1
			INSERT INTO sPurchase.tPurchaseOrderDetail
			(
				Id,
				OrgGroupId,
				PurchaseOrderId,
				PurchaseRequestDetailId,
				StockItemId,
				TotalQty,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberPOD+Id,
					@rOrgGroupId,
					@rId,
					PurchaseRequestDetailId,
					StockItemId,
					TotalQty,
					Remark, 
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tPurchaseOrderDetail PO ON DL.ID = PO.Id
			where PO.PurchaseOrderId = @rId)
			set @lNextNumberPOD=@lNextNumberPOD+(select Count(Id) from @rDetailList where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tPurchaseOrderDetail PO ON DL.ID = PO.Id
			where PO.PurchaseOrderId = @rId))
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseOrderDetail', @rCurrentNumber = @lNextNumberPOD

			Select @rId
		End
		Else
		Begin
		    If Not Exists(
			select PO.Id
			from [sPurchase].[tPurchaseOrder] PO(nolock) 
			Inner Join [sWf].[tWfSetup] WFS on PO.[OrgGroupId] = WFS.[OrgGroupId]
			Where WFS.[WfFunctionalityId] = 3)
			Begin
				Select -102
			End
				Begin
					DECLARE @lNextNumber INT	 
					EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseOrder',@lNextNumber = @lNextNumber output	
					---------------select @lNextNumber
					--DECLARE @loNextNumber nVarchar(20)
					--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
					---------------@rNextNumber = @loNextNumber OUTPUT

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

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

					Select @rId

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

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

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

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

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


GO


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

 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

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

			delete from sPurchase.tPurchaseRequestDetail
			where Id not in(select Id from @rDetailList)
			and PurchaseRequestId = @rId

			update sPurchase.tPurchaseRequestDetail
			set
			OrgGroupId = @rOrgGroupId,
			PurchaseRequestId = @rId,
			StockItemId = DL.StockItemId,
			RequestedQty = DL.RequestedQty,
			Remark = DL.Remark,
			UpdatedUserId = @rUserId,
			UpdatedDateTime = GETUTCDATE()
			from @rDetailList DL
			inner join sPurchase.tPurchaseRequestDetail PR ON DL.ID = PR.Id
			where PR.PurchaseRequestId = @rId

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

			Select @rId
		End
		Else
		Begin
			If Not Exists(
			select PR.Id
			from [sPurchase].[tPurchaseRequest] PR(nolock) 
			Inner Join [sWf].[tWfSetup] WFS on PR.[OrgGroupId] = WFS.[OrgGroupId]
			Where WFS.[WfFunctionalityId] = 1)
			Begin
				Select -102
			End

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

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

			
					select @rId

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

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

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

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

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


GO




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

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

			delete from sPurchase.tQuotationRequestDetail
			where Id not in(select Id from @rDetailList)
			and QuotationRequestId = @rId

			update sPurchase.tQuotationRequestDetail
			set
			OrgGroupId = @rOrgGroupId,
			QuotationRequestId = @rId,
			PurchaseRequestDetailId = DL.PurchaseRequestDetailId,
			StockItemId = DL.StockItemId,
			RequestedQty = DL.RequestedQty,
			Remark = DL.Remark,
			TargetPrice = DL.TargetPrice,
			UpdatedUserId = @rUserId,
			UpdatedDateTime = GETUTCDATE()
			from @rDetailList DL
			inner join sPurchase.tQuotationRequestDetail QR ON DL.ID = QR.Id
			where QuotationRequestId = @rId

			DECLARE @lNextNumberQRDA BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQuotationRequestDetail',@lNextNumber = @lNextNumberQRDA output
			SET @lNextNumberQRDA=@lNextNumberQRDA-1
			INSERT INTO sPurchase.tQuotationRequestDetail
			(
				Id,
				OrgGroupId,
				QuotationRequestId,
				PurchaseRequestDetailId,
				StockItemId,
				RequestedQty,
				Remark,
				TargetPrice,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberQRDA+Id,
				    @rOrgGroupId,
					@rId,
					PurchaseRequestDetailId, 
					StockItemId,
					RequestedQty,
					Remark,
					TargetPrice,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tQuotationRequestDetail QR ON DL.ID = QR.Id
			where QR.QuotationRequestId = @rId)
			set @lNextNumberQRDA=@lNextNumberQRDA+(select Count(Id) from @rDetailList where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tQuotationRequestDetail QR ON DL.ID = QR.Id
			where QR.QuotationRequestId = @rId))
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQuotationRequestDetail', @rCurrentNumber = @lNextNumberQRDA

			select @rId
		End
		Else
		Begin
		    If Not Exists(
			select QR.Id
			from [sPurchase].[tQuotationRequest] QR(nolock) 
			Inner Join [sWf].[tWfSetup] WFS on QR.[OrgGroupId] = WFS.[OrgGroupId]
			Where WFS.[WfFunctionalityId] = 2)
			Begin
				Select -102
			End
				Begin
						DECLARE @lNextNumber INT	 
						EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQuotationRequest',@lNextNumber = @lNextNumber output	
						-------------select @lNextNumber
						--DECLARE @loNextNumber nVarchar(20)
						--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
						-------------@rNextNumber = @loNextNumber OUTPUT
						If not exists(select * from sPurchase.tQuotationRequest where PurchaseRequestId = @rPurchaseRequestId and VendorId = @rVendorId)
						Begin																							
							INSERT INTO sPurchase.tQuotationRequest
							(
								Id,
								Number,
								OrgGroupId,
								BranchId,
								LocationId,
								PurchaseRequestId,
								Name,
								RFQDate,
								Description,
								StartDate,
								EndDate,
								BidOpen,
								BidClose,
								PersonContact,
								Email,
								SendToVendor,
								StatusId,
								VendorId,
								CreatedUserId,		
								CreatedDateTime
	
							)
							VALUES
							(
								@lNextNumber,
								@lNextNumber,
								@rOrgGroupId,
								@rBranchId ,
								@rLocationId,
								@rPurchaseRequestId,
								@rName,
								@rRFQDate,
								@rDescription,
								@rStartDate,
								@rEndDate ,
								@rBidOpen ,
								@rBidClose,
								@rPersonContact,
								@rEmail,
								@rSendToVendor,
								@rStatusId,
								@rVendorId ,
								@rUserId,		
								GETUTCDATE()
							)
 
							set @rId = @lNextNumber 

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

			
							select @rId

							Declare @typeId smallint=0
							Declare @Level smallint=0
							Declare @rActionEmployeeId bigint=0
							SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 2
							IF(@typeId = 1)--parallel
							BEGIN
								exec [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,1,'',0,0,2,@rOrgGroupId
							END
							ELSE IF(@typeId = 2)--sequencial
							Begin
								SELECT @rActionEmployeeId = U.SourceId FROM sSecurity.tUser U WHERE U.Id = @rUserId
								exec [sWf].[pWfApprovalAdd] 0,@rId,2041,@rActionEmployeeId,1,'',1,@Level,2,@rOrgGroupId
							End
							ELSE IF(@typeId = 3)--auto approved
							BEGIN
								exec [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,3,'',0,0,2,@rOrgGroupId
							END
						END
						select -101;

				End
		  End
	COMMIT TRAN -- Transaction Success!	
	END TRY

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

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

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

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


GO

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

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

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

			delete from sPurchase.tSalesReturnDetail
			where Id not in(select Id from @rDetailList)
			and SalesReturnId = @rId

			update sPurchase.tSalesReturnDetail
			set
			OrgGroupId = @rOrgGroupId,
			SalesReturnId = @rId,
			GoodsReceivedNoteDetailId = DL.GoodsReceivedNoteDetailId,
			StockItemId = DL.StockItemId,
			POQty = DL.POQty,
			ReceivedQty = DL.ReceivedQty,
			RejectedQty = DL.RejectedQty,
			CreditNoteIssueDate = DL.CreditNoteIssueDate,
			ReasonForRejection = DL.ReasonForRejection,
			UpdatedUserId = @rUserId,
			UpdatedDateTime = GETUTCDATE()
			from @rDetailList DL
			inner join sPurchase.tSalesReturnDetail SR ON DL.ID = SR.Id
			where SalesReturnId = @rId

			DECLARE @lNextNumberSRD BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tSalesReturnDetail',@lNextNumber = @lNextNumberSRD output
			set @lNextNumberSRD=@lNextNumberSRD-1
			INSERT INTO sPurchase.tSalesReturnDetail
			(
				Id,
				OrgGroupId,
				SalesReturnId,
				GoodsReceivedNoteDetailId,
				StockItemId,
				POQty,
				ReceivedQty,
				RejectedQty,
				CreditNoteIssueDate,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberSRD+Id,
					@rOrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					RejectedQty,
					CreditNoteIssueDate,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tSalesReturnDetail SR ON DL.ID = SR.Id
			where SR.SalesReturnId = @rId)
			set @lNextNumberSRD=@lNextNumberSRD+(select Count(Id) from @rDetailList where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tSalesReturnDetail SR ON DL.ID = SR.Id
			where SR.SalesReturnId = @rId))
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tSalesReturnDetail', @rCurrentNumber = @lNextNumberSRD
			
			select @rId
		End
		Else
		Begin
		    If Not Exists(
                select SR.Id
				from [sPurchase].[tSalesReturn] SR(nolock) 
				Inner Join [sWf].[tWfSetup] WFS on SR.[OrgGroupId] = WFS.[OrgGroupId]
				Where WFS.[WfFunctionalityId] = 5)
				Begin
					Select -102
				End
				Begin
					DECLARE @lNextNumber INT	 
					EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tSalesReturn',@lNextNumber = @lNextNumber output	
					-------------select @lNextNumber
					--DECLARE @loNextNumber nVarchar(20)
					--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
					------------@rNextNumber = @loNextNumber OUTPUT

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

	 				INSERT INTO sPurchase.tSalesReturnDetail
					(
						Id,
						OrgGroupId,
						SalesReturnId,
						GoodsReceivedNoteDetailId,
						StockItemId,
						POQty,
						ReceivedQty,
						RejectedQty,
						CreditNoteIssueDate,
						ReasonForRejection,
						CreatedUserId,
						CreatedDateTime
					)
					select	@lNextNumberSRDD+Id,
							@rOrgGroupId,
							@rId,
							GoodsReceivedNoteDetailId,
							StockItemId,
							POQty,
							ReceivedQty,
							RejectedQty,
							CreditNoteIssueDate,
							ReasonForRejection,
							@rUserId, 
							GETUTCDATE() 
					from @rDetailList
						
					set @lNextNumberSRDD=@lNextNumberSRDD+(select Count(Id) from @rDetailList)
					EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tSalesReturnDetail', @rCurrentNumber = @lNextNumberSRDD
			
					select @rId

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

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

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

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

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO

--Update Old Record for YearlyRegister for AttendanceTypeId
UPDATE sAttendance.tYearlyRegister
SET AttendanceTypeId = 1
WHERE AttendanceTypeId IS NULL


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

