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

GO
PRINT N'Altering Table [sCommon].[tPreviousSchoolMaster]...';


GO
ALTER TABLE [sCommon].[tPreviousSchoolMaster] ALTER COLUMN [Title] NVARCHAR (200) NOT NULL;


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


GO
ALTER VIEW [sCertificate].[vPrintTemplateTransferCertificateReport]
AS
	SELECT
		T.Id,
		SM.Code,
		T.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,
		T.Number,
		T.TCDate,
		T.LeftDate,
		T.LeftDate as [TransferDate],
		T.SemesterDuration,
		T.ExamName,
		T.ExamSeatNo,
		T.ExamYear,
		T.ExamResult,
		T.PromotedClass,
		T.TransferConduct,
		T.OptionalSubject,
		T.Reason,
		T.Remark,
		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,
		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(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,		
		DM.InchargeEmployeeId AS ClassTeacher,
		vSA.BatchName AS BatchName,
		CSM.Title As CasteCategory,
		vSA.BatchId,
		ISNULL(SM.LocalName,'') AS LocalName,	
		CASE WHEN SO.GenderId = 1 Then 'Kumar'
			WHEN SO.GenderId = 2 Then 'Kumari' END AS [Kumar-Kumari],
		CASE WHEN SO.GenderId = 1 Then 'He'
			WHEN SO.GenderId = 2 Then 'She' END AS [He-She],
		CASE WHEN SO.GenderId = 1 Then 'His'
			WHEN SO.GenderId = 2 Then 'Her' END AS [His-Her],
		CASE WHEN SM.StatusId = 1 Then 'is'
			ELSE 'was' END AS [is-was],
		CASE WHEN SO.GenderId = 1 Then 'Mr.'
			WHEN SO.GenderId = 2 Then 'Miss' END AS [Mr-Miss],
		CASE WHEN ISNULL(T.ExamResult,'') = '' THEN ExamName
			ELSE '-' END AS AbsentExamName,
		CASE WHEN ISNULL(T.ExamResult,'') = '' THEN ExamYear
			ELSE '-' END AS AbsentExamYear,
		'[Number],[TCDate],[TransferDate],[SemesterDuration],[ExamName],[ExamSeatNo],[ExamYear],[ExamResult],
		[PromotedClass],[TransferConduct],[OptionalSubject],[Reason],[Remark],
		[FirstName],[MiddleName],[LastName],[FatherName],[MotherName],[Name],[Code],[ClassName],[Divisionname],[DateOfBirth],[DOBInWord],[Kumar-Kumari],[He-She],[His-Her],[is-was],[Mr-Miss],[OrgLogo],[OrgTitle],[SmallAddress1],[SmallAddress2],[RegistrationDetail],[AdhaarNumber],[AbsentExamName],[AbsentExamYear]' As ColumnList

	FROM		
		sCertificate.tTransfer T
		INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=T.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 [sHrm].[vPrintTemplateJoiningCertificateGet]...';


GO

ALTER VIEW [sHrm].[vPrintTemplateJoiningCertificateGet]  

 AS
   
 SELECT   
	EM.Id AS EmployeeId
	,CJ.Number
	,EM.EmployeeName
	,EM.FirstName
	,EM.MiddleName
	,EM.LastName
	,EM.Code
	,EM.ShortName
	,EM.OrgID
	,EM.DepartmentId
	,EM.DepartmentName
	,EM.DesignationId
	,EM.Designation
	,EM.EmployeePhoto
	,EM.DateOfJoining
	,OI.CertificateHeaderA4
	,CJ.Remark  
	,ISNULL(CJ.CertificateDate,'') AS CertificateDate
	,EM.MaritalStatusId
	,CJ.PayScale
	,CJ.AgreementPeriod
	,CJ.CertificateRemark
	,OM.Title As OrgTitle
	,CJ.CreatedDateTime As CreatedDateTime
	,U.DisplayTitle As UserDisplayName
	,EDM.Title AS EmployeeDesignation
	,OM.DisplayTitle As ShortTitle
	,DM.Title AS DepartmentName1
	,EM.MobileNumber
    ,EC.PresentStreetOne  
	,EC.PresentStreetTwo 
	,EC.PresentStreetThree 
	,EC.PresentCity
	,EC.PresentState
	,EC.PresentZipCode
	,EC.PresentContactNo 	
	,ISNULL(EDM1.Title,'Admin') AS UserDesignation   
	,ISNULL(CJ.DateOfJoining,'') As CertificateDateOfJoining
	,EM.GenderId
	,OM.OrgLogo
	,OM.SmallAddress1
	,OM.SmallAddress2
	,OM.RegistrationDetail
	,OM.ReportOrgGroupTitle
	,'[Number],[EmployeeName],[FirstName],[LastName],[Code],[ShortName],[DepartmentName],[Designation],[EmployeePhoto],[DateOfJoining],[CertificateHeaderA4]
	,[Remark],[CertificateDate],[PayScale],[AgreementPeriod],[CertificateRemark],[OrgTitle],[CreatedDateTime],[UserDisplayName]
	,[EmployeeDesignation],[ShortTitle],[DepartmentName1],[MobileNumber],[PresentStreetOne],[PresentStreetTwo],[PresentStreetThree]
	,[PresentCity],[PresentState],[PresentZipCode],[PresentContactNo],[UserDesignation],[CertificateDateOfJoining]
	,[MiddleName],[OrgLogo],[SmallAddress1],[SmallAddress2],[RegistrationDetail],[ReportOrgGroupTitle]' AS ColumnList --MiddleName add for mantis : 0043976

 FROM   
	sHrm.tCertificateJoining CJ   
	INNER JOIN [sHrm].[vExtEmployeeMaster] EM  ON EM.EmployeeId=CJ.EmployeeId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId   
	INNER JOIN  sSecurity.tUser U ON U.Id=CJ.CreatedUserId 
	--AND U.SourceTypeId = 95
	INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.Id
	INNER JOIN  sSetup.tDepartmentMaster DM ON DM.Id=CJ.DepartmentId
	LEFT JOIN  sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId  --added
	LEFT JOIN  sHrm.tEmployeeCommunications EC ON EC.EmployeeId=CJ.EmployeeId  --added
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id 
	LEFT JOIN  sHrm.tEmployeeJobDetail EJD1 ON EJD1.EmployeeId=U.SourceId
	LEFT JOIN  sHrm.tEmployeeDesignationMaster EDM1 ON EDM1.Id=EJD1.EmployeeDesignationId
GO
PRINT N'Creating View [sProcurement].[vExtStockInward]...';


GO
CREATE VIEW [sProcurement].[vExtStockInward]
AS
	SELECT distinct SI.Id AS Id,
			SI.Number AS Number,
			SI.OrgGroupId AS OrgGroupId,
			SI.ToStoreLocationId AS ToStoreLocationId,
			SIM.Code AS Code
		
	FROM sProcurement.tStockInward SI 
		INNER JOIN sProcurement.tStockInwardDetail SID ON SID.StockInwardId=SI.Id
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SID.StockItemId
GO
PRINT N'Altering Function [sCertificate].[fTransferCertificateTemplate]...';


GO


ALTER FUNCTION [sCertificate].[fTransferCertificateTemplate]
(
    @AcademicId BIGINT,
	@BatchId INT,
    @Template NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS

BEGIN
    DECLARE 
        @AdhaarNumber NVARCHAR(20),
        @AdmissionDate DATE,
        @AdmissionStandard NVARCHAR(100),	
		@BankAccountNumber NVARCHAR(20),
		@BankIFSCCode NVARCHAR(20),
		@BankName NVARCHAR(20),
		@BatchDate DATE,
		@BatchName NVARCHAR(100),
		@BirthCountry NVARCHAR(150),
		@DOBInWord NVARCHAR(150),
        @BirthDistrict NVARCHAR(100),
        @BirthPlace NVARCHAR(150),
        @BirthState NVARCHAR(150),
		@BirthTaluka NVARCHAR(150),
		@Caste NVARCHAR(100),
        @CasteCategory NVARCHAR(50),
        @CertificateHeaderA4 NVARCHAR(MAX),
        @City NVARCHAR(100),
        @CityState NVARCHAR(100),
        @ClassName NVARCHAR(100),
		@ClassTeacher NVARCHAR(50),
        @Code NVARCHAR(20),
		@CurrentStandard NVARCHAR(100),
		@CurrentStandardInWords NVARCHAR(100),
		@CurrentStandardTitle NVARCHAR(100),
        @DateOfBirth DATE,
        @DivisionName NVARCHAR(100),
        @DivisionOrder SMALLINT,
        @FatherName NVARCHAR(100),
        @FirstName NVARCHAR(100),
        @LastName NVARCHAR(100),
        @MiddleName NVARCHAR(100),
        @MotherName NVARCHAR(100),
		@MotherTongue NVARCHAR(100),
        @Name NVARCHAR(300),
        @Nationality NVARCHAR(50),
		@NCCScoutDetail NVARCHAR(200),
		@OrgAddress NVARCHAR(152),
        @OrgLogo NVARCHAR(MAX),
        @OrgTitle NVARCHAR(100),
		@PhoneNo NVARCHAR(50),
		@PresentDaysSum SMALLINT,
		@PreviousSchool NVARCHAR(200),
		@PreviousStandard NVARCHAR(50),
		@PromotedorNot NVARCHAR(100),
		@PromotedToClass NVARCHAR(50),
        @RegistrationDetail NVARCHAR(200),
        @Religion NVARCHAR(50),
        @RollNo INT,
        @SmallAddress1 NVARCHAR(200),
        @SmallAddress2 NVARCHAR(200),
        @SubCaste NVARCHAR(100),
		@SubjectNAme NVARCHAR(300),
		@TermsInInstitute NVARCHAR(500),
		@ToCollege NVARCHAR(200),
		@ToCollegeAddress NVARCHAR(200),
		@TotalDaysSum SMALLINT,
		@UIDNumber NVARCHAR(50),
		@University NVARCHAR(200),		
        @LocalName NVARCHAR(100),
		@Number NVARCHAR(50),
		@TCDate DATE,
		@LeftDate DATE,
		@SemesterDuration NVARCHAR(200),
		@ExamName NVARCHAR(200),
		@ExamSeatNo NVARCHAR(50),
		@ExamYear NVARCHAR(50),
		@ExamResult NVARCHAR(50),
		@PromotedClass NVARCHAR(50),
		@TransferConduct NVARCHAR(50),
		@OptionalSubject NVARCHAR(200),
		@Reason NVARCHAR(200),
		@Remark NVARCHAR(200),
		@KumarKumari NVARCHAR(10),
		@HeShe NVARCHAR(10),
		@HisHer NVARCHAR(10),
		@IsWas NVARCHAR(10),
		@MrMiss NVARCHAR(10),
		@AbsentExamName NVARCHAR(200),
		@AbsentExamYear NVARCHAR(50)

    -- Fetch the values from the database
    SELECT
	 
		@Number = ISNULL(Number,''),
		@TCDate = ISNULL(TCDate,''),
		@LeftDate = ISNULL(LeftDate,''),
		@SemesterDuration = ISNULL(SemesterDuration,''),
		@ExamName = ISNULL(ExamName,''),
		@ExamSeatNo = ISNULL(ExamSeatNo,''),
		@ExamYear = ISNULL(ExamYear,''),
		@ExamResult = ISNULL(ExamResult,''),
		@PromotedClass = ISNULL(PromotedClass,''),
		@TransferConduct = ISNULL(TransferConduct,''),
		@OptionalSubject = ISNULL(OptionalSubject,''),
		@Reason = ISNULL(Reason,''),
		@Remark = ISNULL(Remark,''),		
        @AdhaarNumber = ISNULL(AdhaarNumber, ''),
        @AdmissionDate = ISNULL(AdmissionDate, ''),
        @AdmissionStandard = ISNULL(AdmissionStandard, ''),		
		@BankAccountNumber = ISNULL(BankAccountNumber, ''),
		@BankIFSCCode = ISNULL(BankIFSCCode, ''),
		@BankName = ISNULL(BankName, ''),
		@BatchDate = ISNULL(BatchDate, ''),
		@BatchName = ISNULL(BatchName, ''),
		@BirthCountry = ISNULL(BirthCountry, ''),
		@DOBInWord = ISNULL(DOBInWord, ''),
        @BirthDistrict = ISNULL(BirthDistrict, ''),
        @BirthPlace = ISNULL(BirthPlace, ''),
        @BirthState = ISNULL(BirthState, ''),
		@BirthTaluka = ISNULL(BirthTaluka, ''),
		@Caste = ISNULL(Caste, ''),
        @CasteCategory = ISNULL(CasteCategory, ''),
        @CertificateHeaderA4 = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("CertificateHeaderA4")))', 'NVARCHAR(MAX)'),''),
        @City = ISNULL(City, ''),
        @CityState = ISNULL(CityState, ''),
        @ClassName = ISNULL(ClassName, ''),
		@ClassTeacher = ISNULL(ClassTeacher, ''),
        @Code = ISNULL(Code, ''),
		@CurrentStandard = ISNULL(CurrentStandard, ''),
		@CurrentStandardInWords = ISNULL(CurrentStandardInWords, ''),
		@CurrentStandardTitle = ISNULL(CurrentStandardTitle, ''),
        @DateOfBirth = ISNULL(DateOfBirth, ''),
        @DivisionName = ISNULL(Divisionname, ''),
        @DivisionOrder = ISNULL(DivisionOrder, ''),
        @FatherName = ISNULL(FatherName, ''),
        @FirstName = ISNULL(FirstName, ''),
        @LastName = ISNULL(LastName, ''),
        @MiddleName = ISNULL(MiddleName, ''),
        @MotherName = ISNULL(MotherName, ''),
		@MotherTongue = ISNULL(MotherTongue, ''),
        @Name = ISNULL(Name, ''),
        @Nationality = ISNULL(Nationality, ''),
		@OrgAddress = ISNULL(OrgAddress, ''),
        @OrgLogo = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("OrgLogo")))', 'NVARCHAR(MAX)'),''),
        @OrgTitle = ISNULL(OrgTitle, ''),
		@PhoneNo = ISNULL(PhoneNo, ''),
		@PresentDaysSum = ISNULL(PresentDaysSum, 0),
		@PreviousSchool = ISNULL(PreviousSchool, ''),
		@PreviousStandard = ISNULL(PreviousStandard, ''),
        @RegistrationDetail = ISNULL(RegistrationDetail, ''),
        @Religion = ISNULL(Religion, ''),
        @RollNo = ISNULL(RollNo, 0),
        @SmallAddress1 = ISNULL(SmallAddress1, ''),
        @SmallAddress2 = ISNULL(SmallAddress2, ''),
        @SubCaste = ISNULL(SubCaste, ''),
		@TotalDaysSum = ISNULL(TotalDaysSum, 0),
		@UIDNumber = ISNULL(UIDNumber, ''),
		@University = ISNULL(University, ''),	
        @LocalName = ISNULL(LocalName, ''),
		@KumarKumari = ISNULL([Kumar-Kumari],''),
		@HeShe = ISNULL([He-She],''),
		@HisHer = ISNULL([His-Her],''),
		@IsWas = ISNULL([is-was],''),
		@MrMiss = ISNULL([Mr-Miss],''),
		@AbsentExamName = ISNULL(AbsentExamName,''),
		@AbsentExamYear = ISNULL(AbsentExamYear,'')
    FROM 
        sCertificate.vPrintTemplateTransferCertificateReport
    WHERE 
        Academicid = @AcademicId AND BatchId = @BatchId       
	
		SET @Template = REPLACE(@Template, '[Number]', @Number);
		SET @Template = REPLACE(@Template, '[TCDate]', CONVERT(NVARCHAR, @TCDate, 103));
		SET @Template = REPLACE(@Template, '[TransferDate]',CONVERT(NVARCHAR, @LeftDate, 103));
		SET @Template = REPLACE(@Template, '[SemesterDuration]', @SemesterDuration);
		SET @Template = REPLACE(@Template, '[ExamName]', @ExamName);
		SET @Template = REPLACE(@Template, '[ExamSeatNo]', @ExamSeatNo);
		SET @Template = REPLACE(@Template, '[ExamYear]', @ExamYear);
		SET @Template = REPLACE(@Template, '[ExamResult]', @ExamResult);
		SET @Template = REPLACE(@Template, '[PromotedClass]', @PromotedClass);
		SET @Template = REPLACE(@Template, '[TransferConduct]', @TransferConduct);
		SET @Template = REPLACE(@Template, '[OptionalSubject]', @OptionalSubject);
		SET @Template = REPLACE(@Template, '[Reason]', @Reason);
		SET @Template = REPLACE(@Template, '[Remark]', @Remark);		
		SET @Template = REPLACE(@Template, '[FirstName]', @FirstName);		
		SET @Template = REPLACE(@Template, '[MiddleName]', @MiddleName);
		SET @Template = REPLACE(@Template, '[LastName]', @LastName);
		SET @Template = REPLACE(@Template, '[FatherName]', @FatherName);
		SET @Template = REPLACE(@Template, '[MotherName]', @MotherName);
		SET @Template = REPLACE(@Template, '[Name]', @Name);
		SET @Template = REPLACE(@Template, '[Code]', @Code);
		SET @Template = REPLACE(@Template, '[ClassName]', @ClassName);
		SET @Template = REPLACE(@Template, '[Divisionname]', @DivisionName);
		SET @Template = REPLACE(@Template, '[DateOfBirth]', CONVERT(NVARCHAR, @DateOfBirth, 103));
		SET @Template = REPLACE(@Template, '[DOBInWord]', @DOBInWord);
		SET @Template = REPLACE(@Template ,'[Kumar-Kumari]', @KumarKumari);
		SET @Template = REPLACE(@Template ,'[He-She]', @HeShe);
		SET @Template = REPLACE(@Template ,'[His-Her]', @HisHer);
		SET @Template = REPLACE(@Template ,'[is-was]', @IsWas);
		SET @Template = REPLACE(@Template ,'[Mr-Miss]', @MrMiss);
		SET @Template = REPLACE(@Template ,'[OrgLogo]', @OrgLogo);
		SET @Template = REPLACE(@Template ,'[OrgTitle]', @OrgTitle);
		SET @Template = REPLACE(@Template ,'[SmallAddress1]', @SmallAddress1);
		SET @Template = REPLACE(@Template ,'[SmallAddress2]', @SmallAddress2);
		SET @Template = REPLACE(@Template ,'[RegistrationDetail]', @RegistrationDetail);
		SET @Template = REPLACE(@Template ,'[AdhaarNumber]', @AdhaarNumber);
		SET @Template = REPLACE(@Template ,'[AbsentExamName]', @AbsentExamName);
		SET @Template = REPLACE(@Template ,'[AbsentExamYear]', @AbsentExamYear);

		
		RETURN @Template
END;
GO
PRINT N'Altering Function [sHrm].[fEmployeeJoiningCertificateTemplate]...';


GO



ALTER FUNCTION [sHrm].[fEmployeeJoiningCertificateTemplate]
(
	@EmployeeId [bigint]= 0,
    @Template NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE 
        --@EmployeeId  BIGINT,
        @Number INT,
        @EmployeeName NVARCHAR(200),
        @FirstName NVARCHAR(100),
        @MiddleName NVARCHAR(100),
        @LastName NVARCHAR(100),
        @Code NVARCHAR(20),
        @ShortName NVARCHAR(50),
        @DepartmentName NVARCHAR(100),
        @Designation NVARCHAR(100),
        @EmployeePhoto NVARCHAR(MAX),     
        @DateOfJoining DATE,
		@CertificateHeaderA4 NVARCHAR(MAX),

        @Remark NVARCHAR(500),
        @CertificateDate DATE,
        @PayScale NVARCHAR(150),
        @AgreementPeriod NVARCHAR(150),
        @CertificateRemark NVARCHAR(500),
        @OrgTitle NVARCHAR(100),
        @CreatedDateTime DATETIME,
        @UserDisplayName NVARCHAR(100),
        @EmployeeDesignation NVARCHAR(100),
        @ShortTitle NVARCHAR(100),
        @DepartmentName1 NVARCHAR(100),
        @MobileNumber NVARCHAR(20),

        @PresentStreetOne NVARCHAR(150),
        @PresentStreetTwo NVARCHAR(150),
        @PresentStreetThree NVARCHAR(150),
        @PresentCity NVARCHAR(50),
        @PresentState NVARCHAR(50),
        @PresentZipCode NVARCHAR(20),
        @PresentContactNo NVARCHAR(20),
        @UserDesignation NVARCHAR(100),
        @CertificateDateOfJoining DATE,
		@OrgLogo NVARCHAR(MAX),
		@SmallAddress1 NVARCHAR(200),
        @SmallAddress2 NVARCHAR(200),
		@RegistrationDetail NVARCHAR(200),
		@ReportOrgGroupTitle NVARCHAR(200)
        
    -- Fetch the values from the database
    SELECT 
        @EmployeeId = ISNULL(EmployeeId, 0),
        @Number = ISNULL(Number, 0),
        @EmployeeName = ISNULL(EmployeeName, ''),
        @FirstName = ISNULL(FirstName, ''),
        @MiddleName = ISNULL(MiddleName, ''),
        @LastName = ISNULL(LastName, ''),
        @Code= ISNULL(Code, ''),
        @ShortName = ISNULL(ShortName, ''),
        @DepartmentName = ISNULL(DepartmentName, ''),
        @Designation = ISNULL(Designation, ''),
		@EmployeePhoto = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("EmployeePhoto")))', 'NVARCHAR(MAX)'),''),
        @DateOfJoining = ISNULL(DateOfJoining, ''),
        @CertificateHeaderA4 = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("CertificateHeaderA4")))', 'NVARCHAR(MAX)'),''),
        @Remark = ISNULL(Remark, ''),
        @CertificateDate = ISNULL(CertificateDate, ''),
        @PayScale = ISNULL(PayScale, ''),
        @AgreementPeriod = ISNULL(AgreementPeriod, ''),
        @CertificateRemark = ISNULL(CertificateRemark, ''),
        @OrgTitle = ISNULL(OrgTitle, ''),
        @CreatedDateTime = ISNULL(CreatedDateTime, ''),
        @UserDisplayName = ISNULL(UserDisplayName, ''),
        @EmployeeDesignation = ISNULL(EmployeeDesignation, ''),
        @ShortTitle = ISNULL(ShortTitle, ''),
        @DepartmentName1= ISNULL(DepartmentName1, ''),
        @MobileNumber = ISNULL(MobileNumber, ''),
        @PresentStreetOne = ISNULL(PresentStreetOne, ''),
        @PresentStreetTwo = ISNULL(PresentStreetTwo, ''),
        @PresentStreetThree = ISNULL(PresentStreetThree, ''),
        @PresentCity = ISNULL(PresentCity, ''),
        @PresentState = ISNULL(PresentState, ''),
        @PresentZipCode = ISNULL(PresentZipCode, ''),
        @PresentContactNo = ISNULL(PresentContactNo, ''),
        @UserDesignation = ISNULL(UserDesignation, ''),
        @CertificateDateOfJoining = ISNULL(CertificateDateOfJoining, ''),
		@OrgLogo = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("OrgLogo")))', 'NVARCHAR(MAX)'),''),
		@SmallAddress1 = ISNULL(SmallAddress1, ''),
        @SmallAddress2 = ISNULL(SmallAddress2, ''),
		@RegistrationDetail = ISNULL(RegistrationDetail, ''),
		@ReportOrgGroupTitle = ISNULL(ReportOrgGroupTitle, '')
       
    FROM 
      [sHrm].[vPrintTemplateJoiningCertificateGet]  
    WHERE 
        EmployeeId = @EmployeeId

    -- Replace placeholders in the template with actual values
    SET @Template = REPLACE(@Template, '[EmployeeId]', @EmployeeId);
    --SET @Template = REPLACE(@Template, '[AdmissionDate]', CONVERT(NVARCHAR, @AdmissionDate, 103));
    SET @Template = REPLACE(@Template, '[Number]', @Number);
    SET @Template = REPLACE(@Template, '[EmployeeName]', @EmployeeName);
    SET @Template = REPLACE(@Template, '[FirstName]', @FirstName);
    SET @Template = REPLACE(@Template, '[MiddleName]', @MiddleName);
    SET @Template = REPLACE(@Template, '[LastName]', @LastName);
    --SET @Template = REPLACE(@Template, '[BonafideDate]', CONVERT(NVARCHAR, @BonafideDate, 103));
    SET @Template = REPLACE(@Template, '[Code]', @Code);
    SET @Template = REPLACE(@Template, '[ShortName]', @ShortName);
    SET @Template = REPLACE(@Template, '[DepartmentName]', @DepartmentName);
    SET @Template = REPLACE(@Template, '[Designation]', @Designation);
    SET @Template = REPLACE(@Template, '[EmployeePhoto]', @EmployeePhoto);
    SET @Template = REPLACE(@Template, '[DateOfJoining]',CONVERT(NVARCHAR, @DateOfJoining,103));
    SET @Template = REPLACE(@Template, '[CertificateHeaderA4]', @CertificateHeaderA4 );
    SET @Template = REPLACE(@Template, '[Remark]', @Remark);
    SET @Template = REPLACE(@Template, '[CertificateDate]', CONVERT(NVARCHAR,@CertificateDate,103));
    SET @Template = REPLACE(@Template, '[PayScale]', @PayScale);
    SET @Template = REPLACE(@Template, '[AgreementPeriod]', @AgreementPeriod);
    SET @Template = REPLACE(@Template, '[CertificateRemark]', @CertificateRemark);
    SET @Template = REPLACE(@Template, '[OrgTitle]', @OrgTitle);
    SET @Template = REPLACE(@Template, '[CreatedDateTime]', CONVERT(NVARCHAR,@CreatedDateTime,103));
    SET @Template = REPLACE(@Template, '[UserDisplayName]', @UserDisplayName);
    SET @Template = REPLACE(@Template, '[EmployeeDesignation]', @EmployeeDesignation);
    SET @Template = REPLACE(@Template, '[ShortTitle]', @ShortTitle);
    SET @Template = REPLACE(@Template, '[DepartmentName1]', @DepartmentName1);
    SET @Template = REPLACE(@Template, '[MobileNumber]', @MobileNumber);
	SET @Template = REPLACE(@Template, '[PresentStreetOne]', @PresentStreetOne);
    SET @Template = REPLACE(@Template, '[PresentStreetTwo]', @PresentStreetTwo);
	SET @Template = REPLACE(@Template, '[PresentStreetThree]', @PresentStreetThree);
    SET @Template = REPLACE(@Template, '[PresentCity]', @PresentCity);
    SET @Template = REPLACE(@Template, '[PresentState]', @PresentState);
    SET @Template = REPLACE(@Template, '[PresentZipCode]', @PresentZipCode);
	SET @Template = REPLACE(@Template, '[PresentContactNo]', @PresentContactNo);
    SET @Template = REPLACE(@Template, '[UserDesignation]', @UserDesignation);
    SET @Template = REPLACE(@Template, '[CertificateDateOfJoining]',CONVERT(NVARCHAR, @CertificateDateOfJoining,103));
	SET @Template = REPLACE(@Template, '[OrgLogo]', @OrgLogo);
	SET @Template = REPLACE(@Template, '[SmallAddress1]', @SmallAddress1);
	SET @Template = REPLACE(@Template, '[SmallAddress2]', @SmallAddress2);
	SET @Template = REPLACE(@Template, '[RegistrationDetail]', @RegistrationDetail);
	SET @Template = REPLACE(@Template, '[ReportOrgGroupTitle]', @ReportOrgGroupTitle);
    
    RETURN @Template;
END;
GO
PRINT N'Altering Procedure [sAccounting].[pChangeAccountingYear]...';


GO
ALTER   PROCEDURE [sAccounting].[pChangeAccountingYear]
	 
	@rId int,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
 
 BEGIN TRANSACTION	
		--Commented on 19/06/2025 - No OrgId in table
	 --BEGIN	 
	    --UPDATE sAccounting.tAccountingYearMaster SET IsActive = 0 WHERE OrgId = @rOrgId
	 
	    --UPDATE sAccounting.tAccountingYearMaster
	    --SET
	    --  IsActive = 1	      
	    --  WHERE Id = @rId 	   
	 --END  
		SELECT 1 AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAccounting].[pRptExpense]...';


GO
ALTER   PROCEDURE [sAccounting].[pRptExpense]
	
	
	@rFromDate datetime = '1900/1/1',
	@rToDate datetime = '1900/1/1',
	@rExpenseGroupId int,
	@rStoreLocationId int,
	@rOrgId int
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

 	SELECT
 		 E.Id,
 		 E.Amount,
 		 E.ExpenseDate,
 		 E.Remark,
 		 E.ExpenseGroupId,
 		 EGM.Title AS GroupTitle,
		 @rFromDate AS FromDate,
 	     @rToDate AS ToDate
	FROM 
		 sAccounting.tExpense E
		 INNER JOIN sAccounting.tExpenseGroupMaster EGM 
		 ON EGM.Id=E.ExpenseGroupId
			
	   WHERE	
			 
		((E.ExpenseDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((E.ExpenseDate < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND ((E.ExpenseGroupId=@rExpenseGroupId) OR (@rExpenseGroupId=0))
		--AND E.StoreLocationId=@rStoreLocationId --Commented on 19/06/2025 - No StoreLocationId in table
		 
END
GO
PRINT N'Altering Procedure [sAlert].[pStockIssueStudent]...';


GO

 
ALTER PROCEDURE [sAlert].[pStockIssueStudent]
	 	 
		 @rStockIssueId nvarchar(max),
	 	 @rIssueDate Date,
		 @rIssueItem nvarchar(max),
		 @rSourceId BigInt,
	 	 @rBatchId int,	 	 	 	
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),	 	
	 	 @rMailSubject nvarchar(500)='',
		 @rDepositHeadId int = 0 ,			-- Mantis Id : 0044487
		 @rId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	-- #Start Mantis Id : 0044487
	DECLARE @lStudentId bigint, @lDepositHeadName nvarchar(100), @lAmount Decimal(12, 2), @lBalanceAmount Decimal(12, 2), @lRemark nvarchar(300)
	SELECT @lStudentId = StudentId FROM sStudent.tAcademic Where Id = @rSourceId
	SELECT @lDepositHeadName = Title FROM sFee.tDepositHeadMaster WHERE Id = @rDepositHeadId
	SELECT @lAmount = Amount FROM sFee.tDepositAdjustment WHERE ReferenceSourceTypeId = 2039 AND  ReferenceSourceId = @rId
	SELECT @lRemark = Remark FROM sProcurement.tStockIssue WHERE Id = @rId
	SELECT @lBalanceAmount = (SUM(A.DepositAmount) - SUM(A.AdjustAmount) - SUM(A.RefundAmount))
FROM (
	SELECT ISNULL(DA.AMount, 0) AS DepositAmount
		,0 AS AdjustAmount
		,0 AS RefundAmount
		,DepositHeadId
		,SA.StudentId
	FROM sFee.tDepositAdd DA
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = da.AcademicId
	WHERE DA.DepositHeadId = @rDepositHeadId
		AND SA.StudentId = @lStudentId
	
	UNION ALL
	
	SELECT 0 AS DepositAmount
		,ISNULL(AD.Amount, 0) AS AdjustAmount
		,0 AS RefundAmount
		,DepositHeadId
		,SA.StudentId
	FROM sFee.tDepositAdjustment AD
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = AD.AcademicId
	WHERE AD.DepositHeadId = @rDepositHeadId
		AND SA.StudentId = @lStudentId
	
	UNION ALL
	
	SELECT 0 AS DepositAmount
		,0 AS AdONjustAmount
		,Isnull(RefundAmount, 0) AS RefundAmount
		,DepositHeadId
		,SA.StudentId
	FROM sFee.tDepositRefund DR
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = DR.AcademicId
	WHERE DR.DepositHeadId = @rDepositHeadId
		AND SA.StudentId = @lStudentId
	) A
GROUP BY DepositHeadId
	,StudentId;
	-- #End Mantis Id : 0044487

	Select 
			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace(
			replace(
			replace(
			replace(
			replace(
			replace(
			replace(
			replace(
			replace(
			replace(@rTemplate,'[IssueNo]',@rStockIssueId),			
			'[IssueDate]',@rIssueDate),
			'[IssueItem]',@rIssueItem),
			'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[Remark]',ISNULL(@lRemark,'')),
			'[DepositHead]',ISNULL(@lDepositHeadName,'')),
			'[Amount]',ISNULL(@lAmount,0)),
			'[BalanceAmount]',ISNULL(@lBalanceAmount,0))
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			@rStockIssueId AS IssueNo,
			@rIssueDate AS IssueDate,
			@rIssueItem AS IssueItem,
			SC.WhatsAppContactNo
		
	From 
		sStudent.vStudentCommunication SC
	WHERE
	
		 (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
		AND (SC.AcademicId = @rSourceId)
	
END
GO
PRINT N'Altering Procedure [sAssessment].[pExamCombineGet]...';


GO
ALTER   PROCEDURE [sAssessment].[pExamCombineGet]
	 @rClassId int
	,@rExamId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	--Commented on 19/06/2025 - No StoreLocationId in table
	SELECT 
	0 AS ExamCombineId,
    'false' AS CombineSelected,
	0 AS SubExamId ,
	'' AS ExamName,
	0 AS Weightage,
	0 AS ExamOrder

--	SELECT 
--	ISNULL(EC.Id,0) AS ExamCombineId,
--    'false' AS CombineSelected,
--	EM.Id AS SubExamId ,
--	EM.Name AS ExamName,
--	ISNULL(EC.Weightage,0) AS Weightage,
--	ISNULL(ExamOrder,0) AS ExamOrder
--  FROM 
--			[sAssessment].[tExamMaster] EM
--			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
--			LEFT JOIN sAssessment.tExamCombine EC ON EC.ExamId=EM.Id
--WHERE 
--			(CM.Id=@rClassId OR @rClassId=0)  
--			--AND (EM.Id=@rExamId OR @rExamId=0 )
--			AND EM.Id <> @rExamId
--			order by EM.Name ASC
		
END
GO
PRINT N'Altering Procedure [sAssessment].[pExamImportAdd]...';


GO
ALTER   PROCEDURE [sAssessment].[pExamImportAdd]
	
	@rFromBatchId int,
	@rToBatchId int,
	@rOrgId int,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 
	--Commented on 19/06/2025 - Error: Column name or number of supplied values does not match table definition.
	--IF EXISTS ( SELECT 1 FROM sAssessment.tExamMaster WHERE BatchId = @rToBatchId)
	--BEGIN
	--	SELECT -101 AS RESULT
	--	RETURN
	--END

	--BEGIN TRANSACTION
	--Declare @lCount int
	--Declare @lCount2 int
	--DECLARE @lNextNumber INT
	--DECLARE @lNextDetailNumber INT
	--DECLARE @lNextCombineNumber INT
	--DECLARE @lExamSubGroupId int
	--DECLARE @lClassId int 
	--DECLARE @lExamId int
	--Declare @lCountDetail int
	--Declare @lCountCombine int
	
	---- Exam Master Temp Table
	--CREATE TABLE #TempExamMaster(
	--[AutoId] int identity,
	--[Id] [int] NOT NULL,
	--[BatchId] [int] NOT NULL,
	--[ExamSubGroupId] [int] NULL,
	--[ClassId] [int] NOT NULL,
	--[IsRankNo] [bit] NOT NULL,
	--[IsGrade] [bit] NOT NULL,
	--[IsPercentile] [bit] NOT NULL,
	--[IsPercentage] [bit] NOT NULL,
	--[IsSubjectPercentile] [bit] NULL,
	--[GradeSetId] [int] NULL,
	--[RankSetId] [int] NULL,
	--[LevelSetId] [int] NULL,
	--[UpdatedUserId] [bigint] NOT NULL,
	--[UpdatedDateTime] [datetime] NOT NULL,
	--[IsProcessResult] [bit] NULL,
	--[IsMarksInDecimal] [bit] NULL,
	--[IsNegativeMarks] [bit] NULL,
	--[IsIncludeCoScholastic] [bit] NULL,
	--[IsOnPrePrinted] [bit] NULL,
	--[ReportId] [smallint] NULL,
	--[DisplayTitle] [nvarchar](150) NULL,
	--[Remark1] [nvarchar](150) NULL,
	--[Remark2] [nvarchar](150) NULL,
	--[Remark3] [nvarchar](150) NULL,
	--[IsDisplayPhoto] [bit] NULL,
	--[FooterAdjustment] [smallint] NULL,
	--[IsDisplayBirthDate] [bit] NULL,
	--[IsLockForEdit] [bit] NULL,
	--[IsDisplaySchoolName] [bit] NULL,
	--[DetailAdjustment] [smallint] NULL,
	--[IsDisplayHeightWeight] [bit] NULL,
	--[IsDisplayAttendance] [bit] NULL,
	--[TermScopeId] [tinyint] NULL,
	--[IsResultStatus] [bit] NULL,
	--[ExamMaximum] [decimal](6, 2) NULL,
	--[IsDisplayGradeString] [bit] NULL,
	--[IsIncludeGradeSubject] [bit] NULL,
	--[GradeSubjectGradeSetId] [int] NULL,
	--[IsIncludeSubExam] [bit] NULL,
	--[IsCoScholasticGrade] [bit] NULL,
	--[IsCoScholasticGradeIndicator] [bit] NULL,
	--[IsCoScholasticGradeDesIndicator] [bit] NULL,
	--[IsCoScholasticCombine] [bit] NULL,
	--[OldExamId] [int] NULL)
	---- End Create Table
	--INSERT INTO #TempExamMaster SELECT * FROM sAssessment.tExamMaster WHERE BatchId=@rFromBatchId
	--Select @lCount = COUNT(Id) From #TempExamMaster
	--SET  @lCount2 = @lCount 
	--While (@lCount > 0)
	--BEGIN
 
	--SELECT @lExamId=Id,@lClassId=ClassId,@lExamSubGroupId=ExamSubGroupId From #TempExamMaster Where AutoId = @lCount
	
	--IF NOT EXISTS (SELECT 1 FROM sAssessment.tExamMaster WHERE ExamSubGroupId = @lExamSubGroupId AND ClassId =@lClassId AND BatchId = @rToBatchId)
	--BEGIN
	--	-- Exam Master Entry
	--	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		
	--	INSERT INTO sAssessment.tExamMaster 
	--	SELECT 
	--			@lNextNumber,@rToBatchId,ExamSubGroupId,ClassId,IsRankNo,
	--			IsGrade,IsPercentile,IsPercentage,IsSubjectPercentile,CASE WHEN GradeSetId < 0 THEN 0 ELSE GradeSetId END,
	--			RankSetId,LevelSetId,@rCreatedUserId,sCommon.fGetDate(),IsProcessResult,
	--			IsMarksInDecimal,IsNegativeMarks,IsIncludeCoScholastic,IsOnPrePrinted,ReportId,
	--			DisplayTitle,Remark1,Remark2,Remark3,IsDisplayPhoto,FooterAdjustment,IsDisplayBirthDate,
	--			IsLockForEdit,IsDisplaySchoolName,DetailAdjustment,IsDisplayHeightWeight,IsDisplayAttendance,
	--			TermScopeId,IsResultStatus,ExamMaximum,ISNULL(IsDisplayGradeString,0),ISNULL(IsIncludeGradeSubject,0),
	--			ISNULL(GradeSubjectGradeSetId,0),ISNULL(IsIncludeSubExam,0),ISNULL(IsCoScholasticGrade,0),
	--			ISNULL(IsCoScholasticGradeIndicator,0),ISNULL(IsCoScholasticGradeDesIndicator,0),ISNULL(IsCoScholasticCombine,0),Id 
	--	FROM #TempExamMaster Where AutoId = @lCount AND Id =@lExamId AND ClassId=@lClassId AND ExamSubGroupId=@lExamSubGroupId 
	--	-- END Exam Master Entry
		
		
		 
		
		
	--	-- Exam Detail Entry
	--				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamDetail', 0, 1, 1,@outNextNumber = @lNextDetailNumber output
	--				INSERT INTO sAssessment.tExamDetail 
					
	--				SELECT @lNextDetailNumber + ROW_NUMBER() OVER(ORDER BY Id) AS Id,
	--						@lNextNumber,ClassSubjectId,Maximum,Minimum,ISNULL(IsIncludeInTotal,0),ISNULL(IsDisplayInMarksheet,0),
	--						ISNULL(IsShowSubjectGrade,0),DisplayOrder,CASE WHEN GradeSetId < 0 THEN 0 ELSE GradeSetId END,
	--						ExamDate,ExamTime,ExamTopic,@rCreatedUserId,sCommon.fGetDate(),NoOfQuestion,ISNULL(IsShowSubjectMark,0)
							
	--				FROM sAssessment.tExamDetail Where ExamId=@lExamId 					
					
	--				SELECT @lCountDetail = COUNT(Id) FROM sAssessment.tExamDetail Where ExamId=@lExamId						
	--				SET @lNextDetailNumber  = ISNULL(@lCountDetail,0) + @lNextDetailNumber 		
	--				EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tExamDetail', @rCurrentNumber = @lNextDetailNumber 
	--	-- END Exam Detail Entry
		
	--	-- Exam Combine Entry
	--				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamCombine', 0, 1, 1,@outNextNumber = @lNextCombineNumber output
	--				INSERT INTO sAssessment.tExamCombine 
	--				SELECT @lNextCombineNumber + ROW_NUMBER() OVER(ORDER BY Id) AS Id,
	--						@lNextNumber,SubExamId,weightage,ExamOrder,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate()						
	--				FROM sAssessment.tExamCombine Where ExamId=@lExamId 
	--				SELECT @lCountCombine = COUNT(Id) FROM sAssessment.tExamCombine Where ExamId=@lExamId						
	--				SET @lNextCombineNumber  = ISNULL(@lCountCombine,0) + @lNextCombineNumber 		
	--				EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tExamCombine', @rCurrentNumber = @lNextCombineNumber 
	--	-- End Exam Combine Entry
	--	END
	--	Set @lCount = @lCount -1
	--END
	
	
	----While (@lCount > 0)
	----BEGIN
	----SELECT @lExamId=Id  From #TempExamMaster Where AutoId = @lCount
	
	----UPDATE sAssessment.tExamCombine SET SubExamId = 
	----Set @lCount = @lCount -1
	----END
	
	--	 DECLARE @lSubExamId2 int,@lExamId2 int
	
	--CREATE TABLE #TempCombine(
	--[AutoId] int identity,
	--[SubExamId] [int] NOT NULL
	--)
 
 --INSERT INTO #TempCombine
 --SELECT DISTINCT SubExamId  FROM sAssessment.tExamCombine 
 --WHERE  ExamId in (select ID from sAssessment.tExamMaster where BatchId= @rToBatchId AND   OldExamId IS NOT NULL)
 
 --Select @lCount2 = COUNT(AutoId) From #TempCombine
 

	 
	--While (@lCount2 > 0)
	--BEGIN
	--	SELECT @lSubExamId2 = SubExamId   From #TempCombine  Where AutoId = @lCount2
		
	--	SELECT @lExamId2 = Id FROM sAssessment.tExamMaster WHERE OldExamId = @lSubExamId2
		
	--	UPDATE sAssessment.tExamCombine SET SubExamId = @lExamId2 WHERE SubExamId = @lSubExamId2
	--	AND   ExamId in (select id from sAssessment.tExamMaster where BatchId= @rToBatchId AND  OldExamId IS NOT NULL)
	
		 
	--	Set @lCount2 = @lCount2 -1
	--END
 
 
	---- Update Exam Cobine SubExamId
	----UPDATE EC SET EC.SubExamId=EM.ID FROM
	----  sAssessment.tExamCombine EC
	----  INNER JOIN 
	----	sAssessment.tExamMaster EM 
	----	  ON EC.SubExamId = EM.OldExamId 
	----	WHERE EM.BatchId= @rToBatchId AND EM.OldExamId IS NOT NULL
	----	AND EC.ExamId in (select id from sAssessment.tExamMaster where BatchId= @rToBatchId AND  EM.OldExamId IS NOT NULL)
		
	--UPDATE sAssessment.tExamMaster  SET OldExamId = NULL Where BatchId= @rToBatchId
	---- End  Update Exam Cobine SubExamId
	
	
	--Drop Table #TempExamMaster 
	--DROP TABLE #TempCombine
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
Drop Table #TempExamMaster 
DROP TABLE #TempCombine
		ROLLBACK TRANSACTION
		
		SELECT -1 AS Result
END CATCH	
END
GO
PRINT N'Altering Procedure [sAssessment].[pMarkEntrySearchGet]...';


GO
ALTER   PROCEDURE [sAssessment].[pMarkEntrySearchGet]
          
           @rClassId int,
           @rDivisionId int,
           @rExamId int           
          
AS
SET NOCOUNT ON
BEGIN
	SELECT Distinct 0 as ID,'' AS ExamName,'' AS ClassName	
	--Commented on 19/06/2025 - Invalid column name 'Name'.
--SELECT Distinct 0 as ID, EM.Name AS ExamName
--	   ,CM.DisplayTitle AS ClassName	
     
--  FROM [sAssessment].[tResult] R
--		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
--		INNER JOIN sSetup.tClassMaster CM ON CM.Id = EM.ClassId
--		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id 
        
--  WHERE 
--		(CM.Id=@rClassId OR @rClassId=0) AND
--		(DM.Id=@rDivisionId OR @rDivisionId=0)          AND
--		(EM.Id=@rExamId OR @rExamId=0)
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetStandardGet]...';


GO

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

BEGIN 

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

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

--add for 28663 mantis start
DECLARE @lAbsentRemarkConfig nvarchar(20) = ''
SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId
--add for 28663 mantis end
 
	SELECT 
	R.examId,
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		ESGM.Title AS Exam,
		StuM.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		R.AcademicId,			
		R.ResultStatus,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,
		R.Percentile,			
		RD.Id AS ResultDetailId,		
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		RD.Obtain AS SubjectObtain,
		ED.Minimum AS SubjectMinimum,
		ED.Maximum AS SubjectMaximum,
		RD.SubjectGrade,
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		R.Id AS ResultId,
		CS.Id AS SubjectId,			 	
		EM.IsMarksInDecimal,
		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsMarksInDecimal,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		--ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END) AS StudentPhoto,
		RD.IsPresent,
		CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,			
		OM.SmallAddress1,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
		
		EM.IsDisplayTeacherSign,
		Em.IsDisplayPrincipalSign,
		(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
		ELSE NULL END)AS EmployeeSign,
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		--(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		--	OI.CertificateHeaderA4 
		--ELSE 
		--	NULL END) AS MarksheetHeaderA4,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		
		SR.StudentHeight,
		SR.StudentWeight,		
		SR.PresentDays,			
		SR.TotalDays,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.Resultremark3,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		BM.Title AS BatchName,
		Em.DecimalFormat,
		RD.GraceMark,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(BGM.Title,'') AS BloodGroup,
		GS.GradeTitle,
		GS.GradePoint,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		RD.KrupaMark,
		RD.Remark AS OtherDetailRemark,
		ISNULL(SO.AdhaarNumber,'') AS AdharNumber,
		ISNULL(SO.UIDNumber,'') AS UIDNumber,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		(CASE  When EM.IsDisplayAbsentCount=1 then ([sAssessment].[fGetAbsentCount](@rExamId,R.AcademicId, CS.Id)) ELSE 0 END) AS AbsentCount,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = 20438 AND OrgId=A.OrgId),0) AS ReportTemplate,
		StuM.SUId As SUID,
		ISNULL(SO.MotherTongue,'') as MotherTongue,
		CONVERT(bit,@DecimalConfigid) AS IsDecimal,
		ISNULL(Stum.RegistrationNumber,'') as RegistrationNumber,
		EM.IsDisplayHighestDivisionMark,
		EM.ResultSheetAdditionalTitle,
		SR.ExamSeatNo,
		ISNULL(R.ResultIndicator,'') AS ResultIndicator,
		CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,	--add for 28663 mantis
		ISNULL(RD.AbsentRemark,'') AS AbsentRemark,				--add for 28663 mantis
		ISNUll(SF.FatherContactNo,'') AS FatherContactNo,		--Mantis - 0033000
		ISNUll(SF.MotherContactNo,'') AS MotherContactNo,		--Mantis - 0033000
		ISNUll(ED.ExamTopic,'') AS ExamTopic,        --Mantis : 0035823
		ISNULL(StuM.PENNumber, 0 ) AS PENNumber, --Mantis : 36466
		ISNULL(CM1.Title,'') AS StudentCategory, --Added for mantis : 37293
		ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord, --Added for mantis : 37293
		ISNULL(EM.ExamMaximum,0) AS ExamMaximum, --Add for mantis : 0037275
		--Added by dhananjay for mantis - 37594
		ISNULL(StuM.FirstName,'') AS FirstName,
		ISNULL(StuM.LastName,'') AS LastName,
		ISNULL(SGM.Title,'') AS StudentGroup,
		--Added by dhananjay for mantis - 37594
		ISNULL(StuA.AdmissionNumber,0) AS AdmissionNo, -- add for mantis : 0037908
		ED.ExamDate AS ExamDate,   --Mantis - 38799
		--add for 42003 mantis start
		ISNULL(SC.PermanentStreetOne,'') AS PermanentStreetOne,
		ISNULL(SC.PermanentStreetTwo,'') AS PermanentStreetTwo,
		ISNULL(SC.PermanentStreetThree,'') AS PermanentStreetThree,
		--add for 42003 mantis End
		ISNULL(StuM.ApaarIdNumber,'') AS ApaarIdNumber,		--Mantis - 42192
		--Added by dhannanjay mantis : 42409
		ISNULL(RM.Title,'') AS Religion,
		ISNULL(SO.FamilyCast,'') AS FamilyCast,
		ISNULL(SO.FamilySubCast,'') AS FamilySubCast,
		SC.StudentContactNo AS StudentContactNo,
		--Added by dhannanjay mantis : 42409
		--Added by dhannanjay mantis : 42836
		ISNULL(SC.PermanentCountry,'') AS PermanentCountry,
		ISNULL(SC.PermanentState,'') AS PermanentState,
		ISNULL(SC.PermanentCity,'') AS PermanentCity,
		ISNULL(SC.PermanentZipCode,'') AS PermanentZipCode,
		--Added by dhannanjay mantis : 42836
		ISNULL(OM.University,'') AS University
		--Added by dhannanjay mantis : 42925
		--mantis : start : 0045241
		,RAD.SubjectAverageClassMark
		,RAD.SubjectAverageDivisionMark
		,RAD.SubjectHighestClassMark
		--mantis : end : 0045241
	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
		LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		LEFT JOIN scommon.tReligionMaster RM On RM.Id = SO.ReligionId--Added by dhananjay for mantis : 42409
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
		LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId  and RD.SubjectGrade = GS.GradeCode
		LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
		LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId
		LEFT JOIN sCommon.tCastCategoryMaster CM1 ON CM1.Id = SO.CastCategoryId --Added for mantis : 37293
		LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = StuM.StudentGroupId--Added by dhananjay for mantis : 37594
		LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId -- add for mantis : 0037908
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		--AND  ISNULL(EMP.IsOtherUser,0) = 0
		AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		order by A.RollNo,ED.DisplayOrder
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetStandardMultiExamGet]...';


GO

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

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

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

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

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


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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(100),
		StudCode NVarchar(20),
		StudentName Nvarchar(300),
		RollNo int,
		ResultStatus Nvarchar(50),	
		ClassName NVarchar(100),		
		Division NVarchar(100),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(5,2),
		RankNumber int,
		ResultGrade NVarchar(10),
		
		MaximumMark1 decimal(10,2),		
		SubjectGrade1 NVarchar(10),
		--Obtain1 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain1 decimal(5,2),
		ExamMaximum1 decimal(10,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(10,2),	
		SubjectGrade2 NVarchar(10),
		--Obtain2 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain2 decimal(5,2),
		ExamMaximum2 decimal(10,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(10,2),
		SubjectGrade3 NVarchar(10),
		--Obtain3 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain3 decimal(5,2),
		ExamMaximum3 decimal(10,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(10,2),	
		SubjectGrade4 NVarchar(10),
		--Obtain4 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain4 decimal(5,2),
		ExamMaximum4 decimal(10,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(10,2),		
		SubjectGrade5 NVarchar(10),
		--Obtain5 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain5 decimal(5,2),
		ExamMaximum5 decimal(10,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(10,2),		
		SubjectGrade6 NVarchar(10),
		--Obtain6 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain6 decimal(5,2),
		ExamMaximum6 decimal(10,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(10,2),		
		SubjectGrade7 NVarchar(10),
		--Obtain7 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain7 decimal(5,2),
		ExamMaximum7 decimal(10,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(10,2),	
		SubjectGrade8 NVarchar(10),
		--Obtain8 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain8 decimal(5,2),
		ExamMaximum8 decimal(10,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(10,2),		
		SubjectGrade9 NVarchar(10),
		--Obtain9 decimal(5,2) Default 0,	----remove this line and add below line for mantis: 31081
		Obtain9 decimal(5,2),
		ExamMaximum9 decimal(10,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(10,2),		
		SubjectGrade10 NVarchar(10),
		--Obtain10 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain10 decimal(5,2),
		ExamMaximum10 decimal(10,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(10,2),		
		SubjectGrade11 NVarchar(10),
		--Obtain11 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain11 decimal(5,2),
		ExamMaximum11 decimal(10,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(10,2),		
		SubjectGrade12 NVarchar(10),
		--Obtain12 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain12 decimal(5,2),
		ExamMaximum12 decimal(10,2),
		IsPresent12 bit,
		
		MaximumMark13 decimal(10,2),		
		SubjectGrade13 NVarchar(10),
		--Obtain13 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain13 decimal(5,2),
		ExamMaximum13 decimal(10,2),
		IsPresent13 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(10),
		SubjectGradeTerm2 NVarchar(10),
		SubjectGradeTerm3 NVarchar(10),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(300),
		Remark3 nvarchar(300),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(5,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(10),
		PercentileTerm1 decimal(5,2),
		ResultStatusTerm1 Nvarchar(50),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(5,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(10),
		PercentileTerm2 decimal(5,2),
		ResultStatusTerm2 Nvarchar(50), 
		TotalMarkTerm3 	decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(5,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(10),
		PercentileTerm3 decimal(5,2),
		ResultStatusTerm3 Nvarchar(50), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(10),
		SubjectName NVarchar(100),
		SubjectCode Nvarchar(20),	
		SubjectMinimum decimal(10,2),		
		SubjectMaximum decimal(10,2),
		SubjectObtain  decimal(5,2),
		
		Exam1Name Nvarchar(100),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(5,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(10),
		Percentile1 decimal(5,2),
		ResultStatus1 Nvarchar(50),
		Exam1CombineExamName Nvarchar(100),
				
		Exam2Name nvarchar(100),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(5,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(10),
		Percentile2 decimal(5,2),
		ResultStatus2 Nvarchar(50),
		Exam2CombineExamName Nvarchar(100),
		
		Exam3Name nvarchar(100),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(5,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(10),
		Percentile3 decimal(5,2),		
		ResultStatus3 Nvarchar(50),
		Exam3CombineExamName Nvarchar(100),
		
		Exam4Name nvarchar(100),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(5,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(10),
		Percentile4 decimal(5,2),
		ResultStatus4 Nvarchar(50),
		Exam4CombineExamName Nvarchar(100),
		
		Exam5Name nvarchar(100),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(5,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(10),
		Percentile5 decimal(5,2),
		ResultStatus5 Nvarchar(50),
		Exam5CombineExamName Nvarchar(100),
		
		Exam6Name nvarchar(100),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(5,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(10),
		Percentile6 decimal(5,2),
		ResultStatus6 Nvarchar(50),
		Exam6CombineExamName Nvarchar(100),
		
		Exam7Name nvarchar(100),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(5,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(10),
		Percentile7 decimal(5,2),
		ResultStatus7 Nvarchar(50),
		Exam7CombineExamName Nvarchar(100),
		
		Exam8Name nvarchar(100),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(5,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(10),
		Percentile8 decimal(5,2),
		ResultStatus8 Nvarchar(50),
		Exam8CombineExamName Nvarchar(100),
		
		
		Exam9Name nvarchar(100),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(5,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(10),
		Percentile9 decimal(5,2),
		ResultStatus9 Nvarchar(50),
		Exam9CombineExamName Nvarchar(100),
		
		Exam10Name nvarchar(100),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(5,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(10),
		Percentile10 decimal(5,2),
		ResultStatus10 Nvarchar(50),
		Exam10CombineExamName Nvarchar(100),
		
		Exam11Name nvarchar(100),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(5,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(10),
		Percentile11 decimal(5,2),
		ResultStatus11 Nvarchar(50),
		Exam11CombineExamName Nvarchar(100),
		
		Exam12Name nvarchar(100),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(5,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(10),
		Percentile12 decimal(5,2),
		ResultStatus12 Nvarchar(50),
		Exam12CombineExamName Nvarchar(100),

		Exam13Name nvarchar(100),	
		TotalMarks13 decimal(8,2),
		TotalObtain13 decimal(8,2),
		Percentage13 decimal(5,2),
		RankNumber13 int,
		ResultGrade13 NVarchar(10),
		Percentile13 decimal(5,2),
		ResultStatus13 Nvarchar(50),
		Exam13CombineExamName Nvarchar(100),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		Exam13Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(100),
		LastName nvarchar(100),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(50),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(100),
		SubjectGroupCode nvarchar(20),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(100),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(5,2),	
		SubjectObtainTerm2 decimal(5,2),
		SubjectObtainTerm3  decimal(5,2),
		SubjectMaxTerm1 decimal(10,2),
		SubjectMaxTerm2 decimal(10,2),
		SubjectMaxTerm3 decimal(10,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(2000),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(20),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		TotalDays13 decimal(6,2),
		PresentDays13 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(1000),
		GeneralRemarkTerm2 nvarchar(1000),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(6,2),
		SR_WeightTerm1 decimal(6,2),
		SR_HeightTerm2 decimal(6,2),
		SR_WeightTerm2 decimal(6,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(20),
		UIdNumber nvarchar(50),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(50),
		MotherMail nvarchar(50),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(10),
		StreamTitle nvarchar(50),
		AdmissionNo nvarchar(50),
		AdmissionDate Date,
		MiddleName nvarchar(100) ,
		FatherOccupation nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		IsDecimal bit,
		IsAbsentRemark bit,
		FinalAbsentRemark nvarchar(100),
		AbsentRemark1 nvarchar(100),
		AbsentRemark2 nvarchar(100),
		AbsentRemark3 nvarchar(100),
		AbsentRemark4 nvarchar(100),
		AbsentRemark5 nvarchar(100),
		AbsentRemark6 nvarchar(100),
		AbsentRemark7 nvarchar(100),
		AbsentRemark8 nvarchar(100),
		AbsentRemark9 nvarchar(100),
		AbsentRemark10 nvarchar(100),
		AbsentRemark11 nvarchar(100),
		AbsentRemark12 nvarchar(100),
		AbsentRemark13 nvarchar(100),
		ExamMaximumTerm1 decimal(6,2),
		ExamMaximumTerm2 decimal(6,2),
		ExamMaximumTerm3 decimal(6,2),
		--add for 29923 mantis start
		PermanentStreetOne nvarchar(150),
		PermanentStreetTwo nvarchar(150),
		PermanentStreetThree nvarchar(150),
		--add for 29923 mantis end
		CasteCategory nvarchar(50),--Mantis 0030303
		--Mantis Start - 0031091
		FeeCategory nvarchar(100),
		StudentContactNo nvarchar(50),
		--Mantis End - 0031091
		ObtainedMaximum1 decimal(10,2),
		ObtainedMaximum2 decimal(10,2),
		ObtainedMaximum3 decimal(10,2),
		ObtainedMaximum4 decimal(10,2),
		ObtainedMaximum5 decimal(10,2),
		ObtainedMaximum6 decimal(10,2),
		ObtainedMaximum7 decimal(10,2),
		ObtainedMaximum8 decimal(10,2),
		ObtainedMaximum9 decimal(10,2),
		ObtainedMaximum10 decimal(10,2),
		ObtainedMaximum11 decimal(10,2),
		ObtainedMaximum12 decimal(10,2),
		ObtainedMaximum13 decimal(10,2),
		ResultIndicator nvarchar(50),   -- Mantis - 31306
		IsResultIndicator bit,		-- Mantis - 31306
		ExamBlock nvarchar(100), --Mantis - 31848
		AbsentRemarkTerm1 nvarchar(100),    ---Mantis - 32090 - Start
		AbsentRemarkTerm2 nvarchar(100),
		AbsentRemarkTerm3 nvarchar(100),
		IsPresentTerm1 bit,
		IsPresentTerm2 bit,
		IsPresentTerm3 bit ,        ---Mantis - 32090 - End
		--Mantis Start - 0032150
		IsPercentage1 bit,
		IsPercentage2 bit,
		IsPercentage3 bit,
		IsPercentage4 bit,
		IsPercentage5 bit,
		IsPercentage6 bit,
		IsPercentage7 bit,
		IsPercentage8 bit,
		IsPercentage9 bit,
		IsPercentage10 bit,
		IsPercentage11 bit,
		IsPercentage12 bit,
		IsPercentage13 bit,
		BMI decimal(10,2),
		--Mantis End - 0032150
		SubjectGroupOrderIndex smallint,		-- MantisId : 0033292
		RelativeName nvarchar(100), -- Added by dhananjay mantis id : 36622
		SubjectMinTerm1 decimal(10,2), -- add for mantis : 0036630
		SubjectMinTerm2 decimal(10,2), -- add for mantis : 0036630
		SubjectMinTerm3 decimal(10,2),  -- add for mantis : 0036630
		BirthDateInWord nvarchar(150), --added by dhananjay for mantis - 37292
		SchoolStamp varbinary(max),  --Mantis - 38100
		SubjectWiseTeacher nvarchar(max), --Mantis - 38469
		RelativeContactNo nvarchar(50), -- Mantis : 0038696
		FilterWiseOrderBy int, --Added  by dhananjay for mantis : 39391
		PENNumber BigInt, --Added  by dhananjay for mantis : 39863
		ApaarIdNumber nvarchar(50)--Added by dhananjay for mantis : 40247
		,MinimumMark1 decimal(10,2)
		,MinimumMark2 decimal(10,2)
		,MinimumMark3 decimal(10,2)
		,MinimumMark4 decimal(10,2)
		,MinimumMark5 decimal(10,2)
		,MinimumMark6 decimal(10,2)
		,MinimumMark7 decimal(10,2)
		,MinimumMark8 decimal(10,2)
		,MinimumMark9 decimal(10,2)
		,MinimumMark10 decimal(10,2)
		,MinimumMark11 decimal(10,2)
		,MinimumMark12 decimal(10,2)
		,MinimumMark13 decimal(10,2)
		,SubjectRemarkOther Nvarchar(1000), --Added by dhananjay for mantis : 41047
		PresentCity Nvarchar(100), --Mantis - 41591
		--start mantis : 0041741
		IsGrade1 bit,
		IsGrade2 bit,
		IsGrade3 bit,
		IsGrade4 bit,
		IsGrade5 bit,
		IsGrade6 bit,
		IsGrade7 bit,
		IsGrade8 bit,
		IsGrade9 bit,
		IsGrade10 bit,
		IsGrade11 bit,
		IsGrade12 bit,
		IsGrade13 bit,
		--end mantis : 0041741
		--Added by dhannanjay mantis : 42226
		IsDisplayTotalMark1 bit,
		IsDisplayTotalMark2 bit,
		IsDisplayTotalMark3 bit,
		IsDisplayTotalMark4 bit,
		IsDisplayTotalMark5 bit,
		IsDisplayTotalMark6 bit,
		IsDisplayTotalMark7 bit,
		IsDisplayTotalMark8 bit,
		IsDisplayTotalMark9 bit,
		IsDisplayTotalMark10 bit,
		IsDisplayTotalMark11 bit,
		IsDisplayTotalMark12 bit,
		IsDisplayTotalMark13 bit,
		--Added by dhannanjay mantis : 42226
		--Added by dhannanjay mantis : 42409
		Religion nvarchar (50),
		FamilyCast nvarchar (100),
		FamilySubCast nvarchar (100),
		MotherTongue  nvarchar(100),
		--Added by dhannanjay mantis : 42409
		--Added by dhannanjay mantis : 42836
		PermanentCountry nvarchar(50),
		PermanentState  nvarchar(50),
		PermanentCity  nvarchar(50),
		PermanentZipCode  nvarchar(20),
		--Added by dhannanjay mantis : 42836
		--mantis : start : 45242
		SubjectAverageClassMark decimal(5, 2),
		SubjectAverageDivisionMark decimal(5, 2),
		SubjectHighestClassMark decimal(5, 2)
		--mantis : end : 45242

		)
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	
	ExamCode,
	
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	Batch,
	ClassTeacherName,
	FirstName,
	LastName,
	IsDisplayMonthlyAttendance,
	MarksheetHeaderA4,
	IsImageHeader,
	MyGoal,
	AreaOfInterest,
	Responsibility,
	MyInterestHobby,
	MyStrength,
	Achievements, 
	
	DentalHygiene,
	VisionLeft,
	VisionRight,
	IsDetail,
	SubjectGroupId,
	SubjectGroupTitle,
	SubjectGroupCode,
	DecimalFormat,
	SubjectRemark,
	GraceMark,
	KrupaMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText,
    IsShowWithDetail,
    IsPresent,
    GradeTitle,
	
	SubjectHighestDivisionGrade,
	SubjectHighestDivisionMark,
	
	AchievementsTerm1,
	AchievementsTerm2,
	GeneralRemarkTerm1,
	GeneralRemarkTerm2,
	ResultRemark1Term1,
	ResultRemark2Term1,
	ResultRemark1Term2,
	ResultRemark2Term2,
	SR_HeightTerm1,
	SR_WeightTerm1,
	SR_HeightTerm2,
	SR_WeightTerm2,
	SR_PresentDaysTerm1,
	SR_PresentDaysTerm2,
	SR_TotalDaysTerm1,
	SR_TotalDaysTerm2,
	HouseName,
	HouseId,
	AdhaarNumber,
	UIdNumber,
	FatherContactNo ,
	MotherContactNo ,
	FatherMail ,
	MotherMail ,
	Gender,
	CoordinatorEmployeeSign,
	StudentAddress,
	SUId,
	HighestDivisionMark,
	HighestDivisionGrade,
	StreamTitle,
	AdmissionNo,
	AdmissionDate,
	MiddleName ,
	FatherOccupation,
	ResultSheetAdditionalTitle,
	IsDecimal,
	IsAbsentRemark,
	FinalAbsentRemark,
	--Mantis Start - 29923 mantis
	PermanentStreetOne,
	PermanentStreetTwo,
	PermanentStreetThree,
	--Mantis End - 29923 mantis
	CasteCategory,--Mantis 0030303
	
	--Mantis Start - 0031091
		FeeCategory,
		StudentContactNo,
	--Mantis End - 0031091
	ResultIndicator,		-- Mantis - 31306
	IsResultIndicator,		-- Mantis - 31306
	ExamBlock,             --Mantis - 31848
	BMI,
	SubjectGroupOrderIndex,		--MantisId : 0033292
	RelativeName,  -- Added by dhananjay mantis id : 36622
	BirthDateInWord, --added by dhananjay for mantis - 37292
	SchoolStamp,  --Mantis - 38100
	SubjectWiseTeacher, --Mantis - 38469
	RelativeContactNo, -- Mantis : 0038696
	FilterWiseOrderBy,  --Added  by dhananjay for mantis : 39391
	PENNumber,--Added  by dhananjay for mantis : 39863
	ApaarIdNumber, --Added by dhananjay for mantis : 40247
	SubjectRemarkOther, --Added by dhananjay for mantis : 41047
	PresentCity,	--Mantis - 41591
	--Added by dhannanjay mantis : 42409
	Religion,
	FamilyCast,
	FamilySubCast,
	MotherTongue,
	--Added by dhannanjay mantis : 42409
	--Added by dhannanjay mantis : 42836
	PermanentCountry,
	PermanentState,
	PermanentCity,
	PermanentZipCode,
	--Added by dhannanjay mantis : 42836
	--mantis : start : 45242
	SubjectAverageClassMark,
	SubjectAverageDivisionMark,
	SubjectHighestClassMark
		--mantis : end : 45242
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		Convert(nvarchar(50),@rClassId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		ISNULL(R.ResultStatus,'') AS ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		ISNULL(R.Percentage,0) As Percentage,
		R.RankNumber,
		ISNULL(R.ResultGrade,'') AS ResultGrade,


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
		SI.StudentPhoto
		ELSE NULL END)AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		ISNULL(ESGM.Code,'') AS ExamCode,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		 
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		--(CASE EM.IsDisplayImageHeader WHEN 1 THEN
		--	OI.CertificateHeaderA4 
		--	ELSE NULL END)AS  MarksheetHeaderA4,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		@rIsDetail AS IsDetail,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark,
		RD.GraceMark,
		RD.KrupaMark,
		@GradeStringHtml,
		SR.ResultRemark3,
		EM.IsDisplayTotalMark,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		
		'' AS AchievementsTerm1,
		'' AS AchievementsTerm2,
		'' AS GeneralRemarkTerm1,
		'' AS GeneralRemarkTerm2,
		'' AS ResultRemark1Term1,
		'' AS ResultRemark2Term1, 
		'' AS ResultRemark1Term2,
		'' AS ResultRemark2Term2,
		SR.StudentHeight AS SR_HeightTerm1,
		SR.StudentWeight AS SR_WeightTerm1,
		SR.StudentHeight AS SR_HeightTerm2,
		SR.StudentWeight AS SR_WeightTerm2,
		ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm1,
	    ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm2,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm1,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm2,
	    HM.Title As HouseName,HM.Id as HouseId,
	    ISNULL(SO.AdhaarNumber,'') As AdhaarNumber,
	    ISNULL(SO.UIdNumber,'') As UIdNumber,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END)AS Gender,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		(SC.PresentStreetOne +' '+ SC.PresentStreetTwo +' '+ SC.PresentStreetThree +' '+ SC.PresentCity +' '+ SC.PermanentState) AS StudentAddress,
		ISNULL(Stum.SUId,'') AS SUId,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,
		ISNULL(StM.Title,'') AS StreamTitle,
		ISNULL(StuA.AdmissionNumber,0) AS AdmissionNo,
		ISNULL(StuA.AdmissionDate,'') AS AdmissionDate,
		Stum.MiddleName ,
		ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
		ISNULL(EM.ResultSheetAdditionalTitle, '') AS ResultSheetAdditionalTitle,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
		ISNULL(RD.AbsentRemark,'') AS FinalAbsentRemark,
		--add for 29923 mantis start
		SC.PermanentStreetOne,
		SC.PermanentStreetTwo,
		SC.PermanentStreetThree,
		--add for 29923 mantis End
		CSM.Title As CasteCategory,      --Mantis 0030303
		--Mantis Start - 0031091
		ACM.Title AS FeeCategory,
		SC.StudentContactNo AS StudentContactNo,
		--Mantis End - 0031091
		R.ResultIndicator as ResultIndicator, 
		EM.IsDisplayResultIndicator as IsResultIndicator, --Mantis - 31306
		SR.ExamBlock as ExamBlock,        --Mantis - 31848
		CASE
				WHEN ISNULL(AD.HeightAnnual,0)=0 THEN 0
				ELSE CONVERT(decimal(10,2),(ISNULL(AD.WeightAnnual,0)/POWER((ISNULL(AD.HeightAnnual,0)/100),2))) END AS BMI,    -- Mantisid - 0033160
		SG.OrderIndex AS SubjectGroupOrderIndex,			-- MantisId : 0033292
		ISNULL(SF.RelativeName,'') AS RelativeName, -- Added by dhananjay mantis id : 36622
		ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord, --added by dhananjay for mantis - 37292
		OI.SchoolStamp AS SchoolStamp,		--Mantis - 38100
		[sAttendance].[fSubjectTeacherGet](DM.Id,SM.Id) AS SubjectWiseTeacher,		--Mantis - 38469
		ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo ,--add for mantis : 0038696
		@rOrderBy, --Added by dhananjay for Mantis : 39391
		ISNULL(StuM.PENNumber,0) AS PENNumber,--Added  by dhananjay for mantis : 39863
		ISNULL(StuM.ApaarIdNumber,'') AS ApaarIdNumber,--Added  by dhananjay for mantis : 40247
		ISNULL(RDO.Remark,'') AS SubjectRemarkOther, --Added by dhananjay for mantis : 41047
		ISNULL(SC.PresentCity,'') AS City,	--Mantis - 41591
		--Added by dhannanjay mantis : 42409
		ISNULL(RM.Title,'') AS Religion,
		ISNULL(SO.FamilyCast,'') AS FamilyCast,
		ISNULL(SO.FamilySubCast,'') AS FamilySubCast,
		ISNULL(SO.MotherTongue,'') AS MotherTongue,
		--Added by dhannanjay mantis : 42409
		--Added by dhannanjay mantis : 42836
		ISNULL(SC.PermanentCountry,'') AS PermanentCountry,
		ISNULL(SC.PermanentState,'') AS PermanentState,
		ISNULL(SC.PermanentCity,'') AS PermanentCity ,
		ISNULL(SC.PermanentZipCode,'') AS PermanentZipCode
		--Added by dhannanjay mantis : 42836
		--mantis : start : 45242
		,RAD.SubjectAverageClassMark
		,RAD.SubjectAverageDivisionMark
		,RAD.SubjectHighestClassMark
		--mantis : end : 45242
				
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tStreamMaster StM ON CM.StreamId = Stm.Id
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId AND  ISNULL(EMP.IsOtherUser,0) = 0
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	LEFT JOIN scommon.tReligionMaster RM On RM.Id = SO.ReligionId--Added by dhananjay for mantis : 42409
	Left JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId


 



= AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.  TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId        --Mantis 0030303
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id=StuM.AdmissionCategoryId	--Mantis - 0031091
	LEFT JOIN sAssessment.tResultDetailOther RDO ON  RDO.ExamId = EM.Id AND R.Academicid =RDO.AcademicId AND ED.ClassSubjectId = RDO.ClassSubjectId --Added by dhananjay for mantis: 41047
	 
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=0))
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	Order By ED.DisplayOrder

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

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--print ('tempcombine')
	--SELECT * FROM #tempcombineExam
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--SET @lCount1 = @lCount+1
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 --Obtain' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.Obtain,0),	--remove this line and add below line for mantis: 31081
					 Obtain' + convert(nvarchar(15),@lCount)+'= RD.Obtain,
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 AbsentRemark' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.AbsentRemark,' + CHAR(39)+CHAR(39) + '),
					 		
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,

					 ObtainedMaximum' + convert(nvarchar(15),@lCount)+ '= CASE WHEN EM.IsDisplayHighestDivisionMark = 1
									THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
									ELSE 0  END	
					,MinimumMark' + convert(nvarchar(15),@lCount)+ '=ED.Minimum		--add for mantis : 0041047				
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
print(@query)
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.ExamSubGroupDisplayTitle,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0),
					IsPercentage'+convert(nvarchar(15),@lCount)+'=EM.IsPercentage, 
					IsGrade'+convert(nvarchar(15),@lCount)+'=EM.IsGrade,
					IsDisplayTotalMark'+convert(nvarchar(15),@lCount)+'=EM.IsDisplayTotalMark  					
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  --added IsDisplayTotalMark by dhananjay mantis : 42226
						
		execute(@query)
		
		Declare @lCombineExamId int
			SELECT @lCombineExamId = EC.ExamId  FROM [sAssessment].[tExamMaster] EM 
										INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId  
										INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId in (SELECT SubExamId  FROM sAssessment.tExamCombine WHERE examid=@rExamId) 
										WHERE   (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId AND EM.Id = @lSubExamId
			--SELECT @lSubCombineExamName
		set @query ='update T set 
					 Exam' + convert(nvarchar(15),@lCount)+ 'CombineExamName =  EM.DisplayTitle
					  From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lCombineExamId) 
				
				--Print @query		
		execute(@query)
		
	set @lCount = @lCount -1
	end
	

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

	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.*, 0 AS FilterWiseOrderBy,Convert (BigInt, 0)AS PENNumber, '' AS ApaarIdNumber,
	--Convert (decimal, 0) AS MinimumMark1 
	--,Convert (decimal, 0) AS MinimumMark2 
	--,Convert (decimal, 0) AS MinimumMark3 
	--,Convert (decimal, 0) AS MinimumMark4 
	--,Convert (decimal, 0) AS MinimumMark5 
	--,Convert (decimal, 0) AS MinimumMark6 
	--,Convert (decimal, 0) AS MinimumMark7 
	--,Convert (decimal, 0) AS MinimumMark8 
	--,Convert (decimal, 0) AS MinimumMark9 
	--,Convert (decimal, 0) AS MinimumMark10
	--,Convert (decimal, 0) AS MinimumMark11
	--,Convert (decimal, 0) AS MinimumMark12
	--,Convert (decimal, 0) AS MinimumMark13
	--,'' As SubjectRemarkOther
 -- ,'' AS PresentCity,	
	--	Convert (bit,0) AS IsGrade1,
	--	Convert (bit,0) AS IsGrade2,
	--	Convert (bit,0) AS IsGrade3,
	--	Convert (bit,0) AS IsGrade4,
	--	Convert (bit,0) AS IsGrade5,
	--	Convert (bit,0) AS IsGrade6,
	--	Convert (bit,0) AS IsGrade7,
	--	Convert (bit,0) AS IsGrade8,
	--	Convert (bit,0) AS IsGrade9,
	--	Convert (bit,0) AS IsGrade10,
	--	Convert (bit,0) AS IsGrade11,
	--	Convert (bit,0) AS IsGrade12,
	--	Convert (bit,0) AS IsGrade13,
	--	Convert (bit,0) AS IsDisplayTotalmark1,
	--	Convert (bit,0) AS IsDisplayTotalmark2,
	--	Convert (bit,0) AS IsDisplayTotalmark3,
	--	Convert (bit,0) AS IsDisplayTotalmark4,
	--	Convert (bit,0) AS IsDisplayTotalmark5,
	--	Convert (bit,0) AS IsDisplayTotalmark6,
	--	Convert (bit,0) AS IsDisplayTotalmark7,
	--	Convert (bit,0) AS IsDisplayTotalmark8,
	--	Convert (bit,0) AS IsDisplayTotalmark9,
	--	Convert (bit,0) AS IsDisplayTotalmark10,
	--	Convert (bit,0) AS IsDisplayTotalmark11,
	--	Convert (bit,0) AS IsDisplayTotalmark12,
	--	Convert (bit,0) AS IsDisplayTotalmark13,
	--	'' AS Religion, 
	--	'' AS FamilyCast, 
	--	'' AS FamilySubCast,
	--	'' AS MotherTongue,
	--	'' AS PermanentCountry,
	--	'' AS PermanentState,
	--	'' AS PermanentCity ,
	--	'' AS PermanentZipCode,
	--	--mantis : start : 45242
	--	Convert (decimal, 0) AS SubjectAverageClassMark,
	--	Convert (decimal, 0) AS SubjectAverageDivisionMark,
	--	Convert (decimal, 0) AS SubjectHighestClassMark
	--	--mantis : end : 45242

	-- FROM sAssessment.tTempAllExam T
	
	
--end
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultWithSubjectListGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptResultWithSubjectListGet]
	 
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
     @rExamSubGroupId int=0,
	 @rCode nvarchar(20),
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int,
	 @rToRank int,
	 @rGrade nvarchar(20),
	 @rStatusId int = 0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rResultStatus nvarchar(20)='',
	 @rDepartmentId int=0,
	 @rClassStatusId int=0,
	 @rGenderId int = 0
	 ,@rFilterId int=0 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 

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

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SO.GenderId,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ED.IsShowSubjectGrade,
			ED.IsShowSubjectMark,
			(EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName,
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			ISNULL(RD.AbsentRemark,'') AS AbsentRemark,
			ISNULL(StuM.SUId,'') AS SUId, -- Mantis : 0034451
			BM.Title AS BatchName--Added by dhananjay for mantis id - 36257

	FROM 
	
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId =  EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sHrm.tEmployeeMaster EmpM ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.StatusId = 7
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EM.BatchId	 --Added by dhananjay for mantis id - 36257
			--start : mantis : 0045007
			LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND BM.OrgGroupBatchId = AR.OrgGroupBatchId		
			LEFT JOIN
			(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BRD ON BRD.Id=AT.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BRD.BusRouteId AND  AT.SourceTypeId=2003 ) RT
			ON RT.SourceId = StuM.Id AND RT.OrgGroupBatchId = BM.OrgGroupBatchId
			--end : mantis : 0045007
	WHERE 
			
		EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@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 ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))		
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	A.BatchId = @rBatchId 
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0) 
		AND ((SO.GenderId=@rGenderId) OR (@rGenderId=0))
		--AND RD.IsPresent = 0
		--start : mantis : 0045007
		AND 
		(
			(@rFilterId = 0) -- All
			OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
			OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
		) 
		--end : mantis : 0045007
		order by A.RollNo,CS.OrderIndex 

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


GO
ALTER PROCEDURE [sAssessment].[pStudentwiseOptionalSubjectListGet] @rDivisionId BIGINT
	,@rClassId BIGINT
	,@rSubjectId BIGINT
	,@rBatchId INT
	,@rBuilder1 NVARCHAR(max) = ''
	,@rBuilder2 NVARCHAR(max) = ''
	,@rClassStatusId INT = 0
	,@rStatusId INT = 1
	,@rViewMode SMALLINT = 0
	,-- 0 for Vertical and 1 for Horizontal
	@rSubjects NVARCHAR(max) = ''
	,@rDepartmentId INT = 0 --Mantis :0041562 Krunal Patel
AS
SET NOCOUNT ON

BEGIN
	IF (@rViewMode = 1)
	BEGIN
		SELECT SA.AcademicId
			,CS.Id AS ClassSubjectId
			,SA.Name AS StudentName
			,CS.SubjectId
			,SA.Code
			,SA.RollNo
			,SA.DivisionId
			,SA.ClassName
			,SA.DivisionName
		INTO #TempTable
		FROM (
			SELECT *
			FROM sStudent.vStudentAcademic
			WHERE (
					DivisionId = @rDivisionId
					OR @rDivisionId = 0
					)
				AND BatchId = @rBatchId
				AND (
					ClassStatusId = @rClassStatusId
					OR @rClassStatusId = 0
					)
				AND (
					StatusId = @rStatusId
					OR @rStatusId = 0
					)
				AND (
					DepartmentId = @rDepartmentId
					OR @rDepartmentId = 0
					)
				AND (						-- Mantis Id : 0045307 add class filter
					ClassId = @rClassId
					OR @rClassId = 0
					)
			) SA --- Mantis :0041562 Krunal Patel
		CROSS JOIN (
			SELECT *
			FROM sSetup.tClassSubject B
			WHERE B.IsOptional = 1
				AND (
					B.ClassId = @rClassId
					OR @rClassId = 0
					)
				AND (
					B.Id = @rSubjectId
					OR @rSubjectId = 0
					)
			) AS CS

		SELECT DISTINCT SS.AcademicId
			,Stuff((
					SELECT ',' + Convert(NVARCHAR(20), OS.ClassSubjectId)
					FROM sAssessment.tOptionalSubject OS
					WHERE AcademicId = SS.AcademicId
					FOR XML PATH('')
					), 1, 1, '') AS ClassSubjectId
			,SS.StudentName
			,SS.Code
			,SS.RollNo
			,@rBuilder1 AS ClassName
			,@rBuilder2 AS DivisionName
			,SS.DivisionId
			,SS.ClassName AS ClsName
			,SS.DivisionName AS DivName
			,@rSubjects
		FROM #TempTable AS SS
		INNER JOIN sSetup.tSubjectMaster SM ON SS.SubjectId = SM.Id
		LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SS.AcademicId
			AND OS.ClassSubjectId = SS.ClassSubjectId
		ORDER BY SS.RollNo

		DROP TABLE #TempTable
	END
	ELSE
	BEGIN
		SELECT SS.AcademicId
			,SS.ClassSubjectId
			,SS.StudentName
			,SS.SubjectId
			,SM.Code AS SubjectName
			,SS.Code
			,SS.RollNo
			,@rBuilder1 AS ClassName
			,@rBuilder2 AS DivisionName
			,SS.DivisionId
			,SS.ClassName AS ClsName
			,SS.DivisionName AS DivName
			,CASE 
				WHEN isnull(OS.ClassSubjectId, 0) <> 0
					THEN 'true'
				ELSE 'false'
				END AS Selected
		FROM (
			SELECT SA.AcademicId
				,CS.Id AS ClassSubjectId
				,SA.Name AS StudentName
				,CS.SubjectId
				,SA.Code
				,SA.RollNo
				,SA.DivisionId
				,SA.ClassName
				,SA.DivisionName
			FROM (
				SELECT *
				FROM sStudent.vStudentAcademic
				WHERE (
						DivisionId = @rDivisionId
						OR @rDivisionId = 0
						)
					AND BatchId = @rBatchId
					AND (
						ClassStatusId = @rClassStatusId
						OR @rClassStatusId = 0
						)
					AND (
						StatusId = @rStatusId
						OR @rStatusId = 0
						)
					AND (
						DepartmentId = @rDepartmentId
						OR @rDepartmentId = 0
						)
					AND (						-- Mantis Id : 0045307 add class filter
						ClassId = @rClassId
						OR @rClassId = 0
						)
				) SA --- Mantis :0041562 Krunal Patel
			CROSS JOIN (
				SELECT *
				FROM sSetup.tClassSubject B
				WHERE B.IsOptional = 1
					AND (
						B.ClassId = @rClassId
						OR @rClassId = 0
						)
					AND (
						B.Id = @rSubjectID
						OR @rSubjectId = 0
						)
					AND B.IsObsolete = 0 --add IsObsolete for mantisid - 0028508
				) AS CS
			) AS SS
		INNER JOIN sSetup.tSubjectMaster SM ON SS.SubjectId = SM.Id
		LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SS.AcademicId
			AND OS.ClassSubjectId = SS.ClassSubjectId
		ORDER BY SS.RollNo
			,SM.OrderIndex
	END
END
GO
PRINT N'Altering Procedure [sBiometric].[pCloudTransactionDataAdd]...';


GO
ALTER PROCEDURE [sBiometric].[pCloudTransactionDataAdd]
	@rXmlDoc nvarchar(max) = ''

	AS
	SET NOCOUNT ON

BEGIN
	SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
	DECLARE @lInterrorCode INT,
			@intDoc INT

	DECLARE @exceptiondetail NVARCHAR(MAX)

	BEGIN TRY
    BEGIN TRANSACTION;
		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

		CREATE TABLE #tTable(
		TransactionId bigint NOT NULL,
		[PunchId] [nvarchar](50) NOT NULL,
		TransactionDateTime [datetime] NOT NULL,
		[DeviceIP] [nvarchar](20) NOT NULL,
		[Mode] [nvarchar](10) NOT NULL,
		[CreatedDateTime] [datetime] NOT NULL
		)
		INSERT INTO #tTable
		SELECT
			A.TransactionId,
			A.PunchId,
			A.TransactionDateTime,
			A.DeviceIP,
			A.Mode,
			sCommon.fGetDate()
		FROM OPENXML (@intDoc, '/Table/CloudTransactionData', 1)
		WITH
		(
			TransactionId bigint '@TransactionId',
			PunchId nvarchar(50) '@PunchId',
			TransactionDateTime datetime '@TransactionDateTime',
			DeviceIP nvarchar(20) '@DeviceIP',
			Mode nvarchar(10) '@Mode'
		) A

		INSERT INTO sBiometric.tCloudTransactionRawData WITH (rowlock)
		SELECT
			A.TransactionId,
			A.PunchId,
			A.TransactionDateTime,
			A.DeviceIP,
			A.Mode,
			A.CreatedDateTime
		From #tTable A
		Where NOT EXISTS
			(SELECT 1 FROM  sBiometric.tCloudTransactionRawData CRD WITH (NOLOCK) where  A.TransactionDateTime=CRD.TransactionDateTime AND A.PunchId=CRD.PunchId AND A.DeviceIP=CRD.DeviceIP)

		INSERT INTO [sBiometric].[tCloudTransactionData] with (rowlock)
	--Employee
		SELECT
			EM.Id,
			CRD.TransactionDateTime,
			CASE WHEN (SELECT 1 FROM sBiometric.tShiftAllocationCloud WITH (NOLOCK) WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = EM.Id AND SourceTypeId = 95) IS NOT NULL THEN 
			(SELECT top 1 ShiftCode FROM sBiometric.tShiftAllocationCloud WITH (NOLOCK) WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = EM.Id AND SourceTypeId = 95 order by fromShiftDate desc)
			ELSE EM.ShiftId END AS ShiftCode,
			CONVERT(DATE,CRD.TransactionDateTime) AS Attn_Dt,
			CASE WHEN (SELECT TOP 1 ISNULL(Mode,'IN') FROM [sBiometric].[tCloudTransactionData] WITH (NOLOCK) WHERE SourceId = EM.Id AND Attn_Dt = CONVERT(DATE,CRD.TransactionDateTime) ORDER BY In_Out_Time DESC) = 'IN' THEN 'OUT' ELSE 'IN' END AS Mode,
			sCommon.fGetDate(),
			CRD.DeviceIP,
			0,
			CRD.PunchId,
			CRD.TransactionId,
			95,
			0
		FROM
			sBiometric.tCloudTransactionRawData CRD WITH (NOLOCK)
			INNER JOIN sHrm.tEmployeeMaster EM WITH (NOLOCK) ON EM.PunchId = CRD.PunchId
		WHERE
			--mantis: 44582, comment the below condition and add new condition next to it
			--CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData WITH (NOLOCK))
			CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData WITH (NOLOCK) WHERE DeviceIP=CRD.DeviceIP)

		UNION ALL

		--Student
		SELECT
			AC.Id,		--Mantis: 34829, change SM.Id => AC.Id by dhruvik
			CRD.TransactionDateTime,
			CASE WHEN (SELECT 1 FROM sBiometric.tShiftAllocationCloud WITH (NOLOCK) WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = SM.Id AND SourceTypeId = 2003) IS NOT NULL THEN 
			(SELECT top 1 ShiftCode FROM sBiometric.tShiftAllocationCloud WITH (NOLOCK) WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = SM.Id AND SourceTypeId = 2003 order by fromShiftDate desc)
			ELSE SM.ShiftId END AS ShiftCode,
			CONVERT(DATE,CRD.TransactionDateTime) AS Attn_Dt,
			CASE WHEN (SELECT TOP 1 ISNULL(Mode,'IN') FROM [sBiometric].[tCloudTransactionData] WITH (NOLOCK) WHERE SourceId = AC.Id AND Attn_Dt = CONVERT(DATE,CRD.TransactionDateTime) ORDER BY In_Out_Time DESC) = 'IN' THEN 'OUT' ELSE 'IN' END AS Mode,		--Mantis: 34829, change SM.Id => AC.Id by dhruvik
			sCommon.fGetDate(),
			CRD.DeviceIP,
			0,
			CRD.PunchId,
			CRD.TransactionId,
			2001,		--Mantis: 34829, change 2003 => 2001 by dhruvik
			0
		FROM
			sBiometric.tCloudTransactionRawData CRD WITH (NOLOCK)
			INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SM.PunchId = CRD.PunchId
			INNER JOIN sStudent.tAcademic AC WITH (NOLOCK) ON AC.StudentId = SM.Id		--Mantis: 34829, add INNER JOIN by dhruvik
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = AC.BatchId		--Mantis: 34829, add INNER JOIN by dhruvik
		WHERE
			--mantis: 44582, comment the below condition and add new condition next to it
			--CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData WITH (NOLOCK))
			CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData WITH (NOLOCK) WHERE DeviceIP=CRD.DeviceIP)
			AND BM.IsActive = 1		--Mantis: 34829, add condition by dhruvik

		--add for mantis: 10346, start
		INSERT INTO sAudit.tActivityLog
		SELECT TOP 1 * FROM
		(SELECT TOP 1
				OM.OrgGroupId as OrgGroupId,
				EM.OrgId as OrgId,
				3 as UserId,
				'' as SessionId,
				30027 as ScreenId,
				sCommon.fGetDate() as AuditDate,
				'Scheduler-CloudTransactionData' as Activity,
				0 as RecordSourceId,
				'' as RecordDetail,
				3 as OSTypeId
		FROM sBiometric.tCloudTransactionData CTD WITH (NOLOCK)
			INNER JOIN #tTable t ON t.TransactionId = CTD.TransactionId
			INNER JOIN sHrm.tEmployeeMaster EM WITH (NOLOCK) ON EM.PunchId = t.PunchId
			INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = EM.OrgID
		WHERE CTD.SourceTypeId=95

		UNION ALL

		SELECT TOP 1
				OM.OrgGroupId as OrgGroupId,
				SM.OrgId as OrgId,
				3 as UserId,
				'' as SessionId,
				30027 as ScreenId,
				sCommon.fGetDate() as AuditDate,
				'Scheduler-CloudTransactionData' as Activity,
				0 as RecordSourceId,
				'' as RecordDetail,
				3 as OSTypeId
		FROM sBiometric.tCloudTransactionData CTD WITH (NOLOCK)
			INNER JOIN #tTable t ON t.TransactionId = CTD.TransactionId
			INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SM.PunchId = t.PunchId
			INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SM.OrgId
		WHERE CTD.SourceTypeId=2001
		) d

		--add for mantis: 10346, end

		DROP TABLE #tTable
	COMMIT TRANSACTION
	SELECT 1 AS Result
	END TRY

	BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

		SELECT -1 AS Result

		SET @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >
		<tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception ::
		 </td> </tr>
		<tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>
		<td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +','+ '[sBiometric].[tCloudTransactionData]' +'</td></tr>
		</Table>'

		INSERT INTO sSystem.tExceptionLog(OrgGroupId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)
		SELECT 0,'tCloudTransactionData_DbError,'+ ' [sBiometric].[tCloudTransactionData]',ERROR_MESSAGE(),@exceptiondetail,sCommon.fGetDate()
		RETURN
    END CATCH
END
GO
PRINT N'Altering Procedure [sCertificate].[pStudentCustomFiledDataGet]...';


GO

ALTER PROCEDURE [sCertificate].[pStudentCustomFiledDataGet]
	 
	 @rAcademicId bigint = 0,
	 @rOrgGroupId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @lStudentId BigInt = 0;
SELECT @lStudentId = StudentId FROM sStudent.tAcademic WHERE Id = @rAcademicId

DECLARE @columns NVARCHAR(MAX);
DECLARE @sql NVARCHAR(MAX);

	SET @columns = STUFF(
		(
			SELECT ',' + QUOTENAME(LTRIM(RTRIM(FieldTitle)))
			FROM sStudent.tStudentCustomFieldMaster SM
			LEFT JOIN sStudent.tStudentCustomFieldData CM ON SM.Id = CM.StudentCustomFieldId AND CM.StudentId = @lStudentId
			WHERE SM.OrgGroupId = @rOrgGroupId AND SM.IsObsolete = 0
			GROUP BY FieldTitle
			FOR XML PATH(''), TYPE
		).value('.', 'NVARCHAR(MAX)')
		,1,1,''); -- Remove the leading comma


-- Construct the dynamic SQL query
	SET @sql = '
	SELECT StudentId, ' + @columns + '
	FROM
	(
		SELECT 
			CM.StudentId,
			LTRIM(RTRIM(SM.FieldTitle)) AS FieldTitle,
			CASE WHEN ISNULL(CM.FieldData, '''') = ''- Select -'' THEN ''''
                ELSE ISNULL(CM.FieldData, '''') END AS FieldData
		FROM sStudent.tStudentCustomFieldMaster SM
		LEFT JOIN sStudent.tStudentCustomFieldData CM ON SM.Id = CM.StudentCustomFieldId AND CM.StudentId = ' + Convert(varchar(20),@lStudentId) + ' 
		WHERE SM.OrgGroupId = ' + Convert(varchar(10),@rOrgGroupId) + ' AND SM.IsObsolete = 0 AND CM.StudentId IS NOT NULL
	) AS SourceTable
	PIVOT
	(
		MAX(FieldData)
		FOR FieldTitle IN (' + @columns + ')
	) AS PivotTable
	';

-- Print the SQL for debugging
	--PRINT @sql;

-- Execute the dynamic SQL
	EXEC sp_executesql @sql;

END
GO
PRINT N'Altering Procedure [sCommon].[pAreaAndCityGet]...';


GO
ALTER   PROCEDURE [sCommon].[pAreaAndCityGet]
	@rOrgId [int],
	@rAreaId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
SET @rOrgId = 0
	SELECT 0 AS CityId, '' AS Title
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--SELECT ISNULL(AM.CityId, 0), ISNULL(CM.Title, '') 
	--FROM sCommon.tAreaMaster AM
	--LEFT JOIN sCommon.tCityMaster CM ON CM.Id = AM.CityId
	-- WHERE AM.Id = @rAreaId AND AM.OrgId = @rOrgId
END
GO
PRINT N'Altering Procedure [sCommon].[pAreaMasterList]...';


GO
ALTER   PROCEDURE [sCommon].[pAreaMasterList]
	@rOrgId [int],
	@rCityId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
SET @rOrgId = 0

	 SELECT 0 AS Id,			
			0 AS Title
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	  -- FROM sCommon.tAreaMaster
	  --WHERE ((CityId = @rCityId) OR (@rCityId = 0)) 
	  --AND OrgId = @rOrgId
			
END
GO
PRINT N'Altering Procedure [sCommon].[pCityMasterSearch]...';


GO
ALTER   PROCEDURE [sCommon].[pCityMasterSearch]
	@rOrgId int,
	@rCityTitle [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON;
BEGIN
	SELECT	'' AS Title, 
			0 AS Id, 
			0 AS StateId, 
			0 ASIsObsolete, 
			'' AS StateName
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.

-------IF(@rFlag = 1)
----	BEGIN
----			SELECT	
----				CM.Title Title, 
----				CM.ID AS Id, 
----				CM.StateId, 
----				CM.IsObsolete, 
----				sCommon.tStateMaster.Title StateName
----			FROM sCommon.tStateMaster 
----				INNER JOIN sCommon.tCityMaster CM
----					ON CM.StateId = sCommon.tStateMaster.Id
----			WHERE 
----				CM.Title LIKE @rCityTitle
----			----AND sCommon.tStateMaster.Id = @rStateId
----	END
-------ELSE
--	BEGIN
--	SET @rOrgId = 0

--		---IF(@rStateId <= 0)
--			BEGIN
--				SELECT	
--					CM.Title Title, 
--				    CM.ID AS Id, 
--				    CM.StateId, 
--				    CM.IsObsolete, 
--				    sCommon.tStateMaster.Title StateName
--			FROM sCommon.tStateMaster 
--				INNER JOIN sCommon.tCityMaster CM
--					ON CM.StateId = sCommon.tStateMaster.Id
--				WHERE
--					CM.Title LIKE @rCityTitle + '%'
--					AND CM.OrgId = @rOrgId
--			END
-------ELSE
----			BEGIN
----				SELECT	
----				    CM.Title Title, 
----				    CM.ID AS Id, 
----				    CM.StateId, 
----				    CM.IsObsolete, 
----				    sCommon.tStateMaster.Title StateName
----			FROM sCommon.tStateMaster  
----				INNER JOIN sCommon.tCityMaster CM
----					ON CM.StateId = sCommon.tStateMaster.Id
----					WHERE 
----						CM.Title LIKE @rCityTitle 
----					OR sCommon.tStateMaster.Id = @rStateId
----			END
			
	END
GO
PRINT N'Altering Procedure [sCommon].[pCompanySetupAdd]...';


GO
ALTER   PROCEDURE [sCommon].[pCompanySetupAdd]
    @rOrgId int    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SELECT 0 AS Result
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
--SET @rOrgId = @rOrgId
--DECLARE @lCreatedDateTime DATETIME
--SET @lCreatedDateTime =  GETDATE()

--DECLARE @lCreatedUserId Int
--SET @lCreatedUserId = 1
--BEGIN TRY
--BEGIN TRANSACTION

 
 
-- INSERT INTO [sCommon].[tTableRowId]
--           ([OrgId]
--           ,[TableTitle]
--           ,[CurrentNumber]
--           ,[Seed]
--           ,[Increment])
--SELECT
--		   @rOrgId
--		  ,[TableTitle]
		  
--		  ,CASE 
--      WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(CurrentNumber,@rOrgId) 
--      WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(CurrentNumber,@rOrgId )
--		END 
		
--		  ,CASE 
--      WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(CurrentNumber,@rOrgId) 
--      WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(CurrentNumber,@rOrgId )
--		END  
--		   ,1
--	  FROM [sCommon].[tTableRowIdMaster] where 
--	  (tableType = 'Non Static' or tableType = '100Static' )
--	  AND iddatatype <> ''
	  
	
--	INSERT INTO [sCommon].[tTableRowId]
--           ([OrgId]
--           ,[TableTitle]
--           ,[CurrentNumber]
--           ,[Seed]
--           ,[Increment])
--SELECT
--		   0
--		  ,[TableTitle]		  
--		  ,CurrentNumber		
--		  ,CurrentNumber
--		  ,1
--	  FROM [sCommon].[tTableRowIdMaster] where 
--	  (tableType =   '100StaticCommon')  
 
 
 
-- INSERT INTO [sSetup].[tBatchMaster]
--           ([Id]
--           ,[Code]
--           ,[Title]
--           ,[OrgId]
--           ,[IsHistory]
--           ,[IsActive]
--           ,[IsObsolete]
--           ,[OrderIndex]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime])
     
--      SELECT sCommon.fGetIntIdForOrg(Id,@rOrgId)
--           ,[Code]
--           ,[Title]
--           ,@rOrgId
--           ,[IsHistory]
--           ,[IsActive]
--           ,[IsObsolete]
--           ,[OrderIndex]
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--           FROM [sSetup].[tBatchMaster] WHERE  OrgId =  1
 
  


-- INSERT INTO [sIp].[tStoreLocationMaster]
--          ([OrgId]
--           ,[Id]
--           ,[Code]
--           ,[Title]
--           ,[IsObsolete]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           ,[LocationId]
--           ,[IsShowDependent])
--	SELECT
--	   @rOrgId
--      ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
--      ,[Code]
--      ,[Title]
--      ,[IsObsolete]
--      ,@lCreatedUserId
--	  ,@lCreatedDateTime
--	  ,@lCreatedUserId
--	  ,@lCreatedDateTime
--      ,sCommon.fGetIntIdForOrg(LocationId,@rOrgId)
--      ,[IsShowDependent]
--  FROM [sIp].[tStoreLocationMaster] WHERE OrgId =1
  
  

 

	
		  
 


 
  
   
  
--  INSERT INTO  [sCommon].[tCountryMaster]
--           ([OrgId]
--           ,[Title]
--           ,[Nationality]
--           ,[IsObsolete]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           ,[Id]
--           ,[IsShow])
--     SELECT
--            @rOrgId
--           ,[Title]
--           ,[Nationality]
--           ,[IsObsolete]
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--           ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
--           ,[IsShow]
--FROM [sCommon].[tCountryMaster] WHERE  OrgId = 1



-- INSERT INTO [sCommon].[tLocationMaster]
--           ([Id]
--           ,[OrgId]
--           ,[Code]
--           ,[Title]
--           ,[StreetOne]
--           ,[StreetTwo]
--           ,[StreetThree]
--           ,[CityName]
--           ,[StateName]
--           ,[CountryName]
--           ,[ZipCode]
--           ,[PhoneNo]
--           ,[FaxNo]
--           ,[NameOfOccupier]
--           ,[AddressOfOccupier]
--           ,[SmallAddress1]
--           ,[SmallAddress2]
--           ,[RegistrationNumber]
--           ,[LicenceNumber]
--           ,[EsicNumber]
--           ,[EsicAddress1]
--           ,[EsicAddress2]
--           ,[NatureOfIndustry]
--           ,[ByProduct]
--           ,[DangerousOperation]
--           ,[NatureOfTest]
--           ,[NatureOfTestNonHazardous]
--           ,[RowMaterialUsed]
--           ,[HazardousProcess]
--           ,[Cmo]
--           ,[NicNumber]
--           ,[IsObsolete]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           ,[CountryId]
--           ,[StateId])
           
--  SELECT sCommon.fGetIntIdForOrg(Id,@rOrgId)
--      ,@rOrgId
--      ,[Code]
--      ,[Title]
--      ,[StreetOne]
--      ,[StreetTwo]
--      ,[StreetThree]
--      ,[CityName]
--      ,[StateName]
--      ,[CountryName]
--      ,[ZipCode]
--      ,[PhoneNo]
--      ,[FaxNo]
--      ,[NameOfOccupier]
--      ,[AddressOfOccupier]
--      ,[SmallAddress1]
--      ,[SmallAddress2]
--      ,[RegistrationNumber]
--      ,[LicenceNumber]
--      ,[EsicNumber]
--      ,[EsicAddress1]
--      ,[EsicAddress2]
--      ,[NatureOfIndustry]
--      ,[ByProduct]
--      ,[DangerousOperation]
--      ,[NatureOfTest]
--      ,[NatureOfTestNonHazardous]
--      ,[RowMaterialUsed]
--      ,[HazardousProcess]
--      ,[Cmo]
--      ,[NicNumber]
--      ,[IsObsolete]
--    ,@lCreatedUserId
--  ,@lCreatedDateTime
--  ,@lCreatedUserId
--  ,@lCreatedDateTime
--      ,sCommon.fGetIntIdForOrg(CountryId,@rOrgId) 
--      ,sCommon.fGetIntIdForOrg(StateId,@rOrgId) 
--  FROM [sCommon].[tLocationMaster]  where OrgId=1   	




--INSERT INTO  [sCommon].[tStateMaster]
--           ([OrgId]
--           ,[CountryId]
--           ,[Title]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           ,[IsObsolete]
--           ,[Id]
--           ,[IsShow])
--     sELECT
--			@rOrgId
--           ,sCommon.fGetIntIdForOrg(CountryId,@rOrgId)
--           ,[Title]
--		   ,@lCreatedUserId
--		   ,@lCreatedDateTime
--		   ,@lCreatedUserId
--		   ,@lCreatedDateTime
--           ,[IsObsolete]
--           ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
--           ,[IsShow] 
--FROM [sCommon].[tStateMaster] wHERe OrgId = 1

 
-- INSERT INTO [sSecurity].[tPermission]
--           ([TaskId]
--           ,[RoleId]
--           ,[Permission]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           ,[IsObsolete]
--           ,[OrgId])
--	SELECT
--	      [TaskId]
--           ,sCommon.fGetIntIdForOrg(RoleId,@rOrgId)
--           ,[Permission]
--           ,@lCreatedUserId
--		   ,@lCreatedDateTime
--		   ,@lCreatedUserId
--	       ,@lCreatedDateTime
--           ,[IsObsolete]
--           ,@rOrgId
--	  FROM [sSecurity].[tPermission] WHERE RoleId = 2 AND OrgId = 1
 
 
-- INSERT INTO [sSecurity].[tRole]
--           ([Id]
--           ,[Title]
--           ,[Remark]
--           ,[IsObsolete]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           ,[IsSystem]
--           ,[OrgId])
--	SELECT
--		   sCommon.fGetIntIdForOrg(Id,@rOrgId)
--		  ,[Title]
--		  ,[Remark]
--		  ,[IsObsolete]
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--		  ,[IsSystem]
--		  ,@rOrgId
--	  FROM [sSecurity].[tRole] WHere OrgId=1          
 
--	  INSERT INTO sSecurity.tUser 
--		   ([Id]
--           ,[DisplayTitle]
--           ,[LoginTitle]
--           ,[LoginPassword]
--           ,[LastLockOutDate]
--           ,[NumberOfLogonAttempt]
--           ,[IsObsolete]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           --,[EmployeeId]
--           ,[SessionId]
--           ,[OrgId])		  
--	SELECT 
--		   sCommon.fGetBigIntIdForOrg(Id,@rOrgId)
--		  ,[DisplayTitle]
--		  ,[LoginTitle]
--		  ,[LoginPassword]
--		  ,@lCreatedDateTime
--		  ,[NumberOfLogonAttempt]
--		  ,[IsObsolete]
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--		  --,sCommon.fGetIntIdForOrg(1,@rOrgId)
--		  ,[SessionId]
--		  ,@rOrgId
--	  FROM [sSecurity].[tUser] WHERE Id < 4 AND OrgId=1

  
-- --INSERT INTO [sSecurity].[tUserLocation]
-- --          ([StoreLocationId]
-- --          ,[UserId]
-- --          ,[CreatedUserId]
-- --          ,[CreatedDateTime])
           
-- --  select 
--	--sCommon.fGetIntIdForOrg(Id,@rOrgId),
--	--sCommon.fGetBigIntIdForOrg(3,@rOrgId)
--	--,@lCreatedUserId
--	--,@lCreatedDateTime
-- --from sIp.tStoreLocationMaster where OrgId=1   	
 
 
----OrgId is not used
--INSERT INTO [sSecurity].[tUserRole]
--           (
--            [RoleId]
--           ,[UserId]
--           ,[IsObsolete]
--           ,[CreatedUserId]
--           ,[CreatedDateTime]
--           ,[UpdatedUserId]
--           ,[UpdatedDateTime]
--           )
--SELECT 
--		   sCommon.fGetIntIdForOrg(2,@rOrgId)
--		  ,sCommon.fGetBigIntIdForOrg(3,@rOrgId)
--		  ,0
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime
--		  ,@lCreatedUserId
--		  ,@lCreatedDateTime

 

 

 


--INSERT INTO [sConfig].[tColorLegendDetail]
--           ([OrgId]
--           ,[Id]
--           ,[Title]
--           ,[ColorLegendId]
--           ,[configSettingId])
--	SELECT
--		   @rOrgId
--		  ,sCommon.fGetIntIdForOrg(Id,@rOrgId)
--		  ,[Title]
--		  ,[ColorLegendId]
--		  ,[configSettingId]
--	  FROM [sConfig].[tColorLegendDetail] WHERE OrgId=1
	  
 
	      

--COMMIT TRANSACTION	 
--END TRY
--BEGIN CATCH
--ROLLBACK TRANSACTION
--SELECT ERROR_MESSAGE()
--END CATCH
END
GO
PRINT N'Altering Procedure [sCommon].[pCountryMasterValidate]...';


GO
ALTER   PROCEDURE [sCommon].[pCountryMasterValidate]
    @rOrgId [int],
	@rTitle [nvarchar](20)
WITH EXECUTE AS CALLER
AS

SET @rOrgId = 0
DECLARE @lCountryId INT
SET @lCountryId = 0

SET NOCOUNT ON

BEGIN

--Commented on 19/06/2025 - Invalid column name 'OrgId'.
--	SELECT @lCountryId = Id
--	FROM sCommon.tCountryMaster 
--	WHERE (
--			--UPPER(Code) = UPPER(@rCode) 
--			 UPPER(Title) = UPPER(@rTitle)
----			UPPER(Nationality) = UPPER(@rNationality) 
--		  )  
--		AND IsObsolete = 0
--		AND OrgId = @rOrgId
 
--	IF @lCountryId > 0
--		SELECT 0 AS Result
--	ELSE
		SELECT 1 AS Result
----	BEGIN
----		SELECT @lCountryId, @rCode 

END
GO
PRINT N'Altering Procedure [sCommon].[pGeneralMasterDataWithValueModify]...';


GO

ALTER PROCEDURE [sCommon].[pGeneralMasterDataWithValueModify]
	@rTableName [nvarchar](100),
	@rIDField [nvarchar](100),
	@rCodeField [nvarchar](100),
	@rRemarkField [nvarchar](100),
	@rId [int],
	@rCode [nvarchar](100),
	@rRemark [nvarchar](200),--mantis : 0044848 : nvarchar(100) to 200
	@rIsObsolete [smallint],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN
	DECLARE @lSelectClause Nvarchar(2000)
	SET @lSelectClause =     ' UPDATE ' + 	@rTableName + 
							   ' SET ' +  	
										  @rCodeField + ' = N''' + @rCode + ''' ' + ',' +
									      @rRemarkField + ' = N''' + CONVERT(NVARCHAR(200),@rRemark) + ''' ,
										  IsObsolete = ' + CONVERT(NVARCHAR(7), @rIsObsolete) + ' ,  		
									      UpdatedUserId = ' + CONVERT(NVARCHAR(25), @rUpdatedUserId) + ' ,  
										  UpdatedDateTime = ''' + CONVERT(NVARCHAR(32), sCommon.fGetDate() )  + ''' 
										  WHERE ' + @rIDField + ' = ' + CONVERT(NVARCHAR(10), @rId )	+

							'  IF @@ROWCOUNT > 0    
								BEGIN
									SELECT 1 AS Result
								END
							ELSE    
								BEGIN
									SELECT 0 AS Result
								END'


--SELECT 	@lSelectClause

	EXECUTE sp_executesql @lSelectClause


END
GO
PRINT N'Altering Procedure [sCommon].[pStateMasterByCountryIdGet]...';


GO
ALTER   PROCEDURE [sCommon].[pStateMasterByCountryIdGet]
    @rOrgId [int],
	@rCountryId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rOrgId = 0
BEGIN
	SELECT	0 AS Id, 
			0 AS Title 
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--SELECT	Id, 
	--		Title 
	--FROM sCommon.tStateMaster 
	--WHERE 
	--	(IsObsolete = 0 OR IsObsolete IS NULL) 
	--	AND OrgId = @rOrgId
	--	ORDER BY Title 	 
END
GO
PRINT N'Altering Procedure [sCommon].[pTableRowIdModify]...';


GO

ALTER PROCEDURE [sCommon].[pTableRowIdModify]
@rOrgGroupId [int],
@rTableTitle [nvarchar](100),
@rCurrentNumber [bigint] = NULL,
@rSeed [bigint] = NULL,
@rIncrement [bigint] = NULL,
@rIsCurrentNumber [bit] = 0,
@rNextNumber [bigint] = NULL OUTPUT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
Begin tran
declare @exceptiondetail nvarchar(max)
	IF @rCurrentNumber > 0
	BEGIN
		UPDATE sCommon.tTableRowId WITH (rowlock) SET CurrentNumber = @rCurrentNumber
		--,UpdatedDateTime = sCommon.fGetDate() 
		WHERE TableTitle = @rTableTitle AND OrgId = @rOrgGroupId
	END
	ELSE
	BEGIN 
		UPDATE sCommon.tTableRowId WITH (rowlock) 
		SET @rNextNumber = CurrentNumber = (CASE @rIsCurrentNumber WHEN 1 THEN CurrentNumber ELSE 
		                                   (CASE WHEN CurrentNumber < Seed THEN Seed ELSE CurrentNumber + Increment END) END),
		Seed = ISNULL(@rSeed, Seed),
		Increment = ISNULL(@rIncrement, Increment),
		UpdatedDateTime = sCommon.fGetDate()
		WHERE TableTitle = @rTableTitle AND OrgId = @rOrgGroupId
	END
	commit tran
END TRY
BEGIN CATCH
 	
rollback tran
set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >
<tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception ::
 </td> </tr>
<tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>
<td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +','+ @rTableTitle +'</td></tr>
</Table>'
 
		insert into sSystem.tExceptionLog(OrgGroupId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)
		Select @rOrgGroupId,'TableRowId_DBError,'+ @rTableTitle,ERROR_MESSAGE(),@exceptiondetail,sCommon.fGetDate()	
Return
END CATCH

END
GO
PRINT N'Altering Procedure [sProcurement].[pPurchaseOrderDetailModify]...';


GO
ALTER   PROCEDURE [sProcurement].[pPurchaseOrderDetailModify]
    @rOrgId int,
	@rPurchaseOrderId [bigint],
	@rPurchaseOrderDetailXml [nvarchar](max),
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--DECLARE @loIdoc INT
	--DECLARE @lPurchaseOrderDetailCurrentId BIGINT
	--DECLARE @lCount BIGINT
		
	--EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rPurchaseOrderDetailXml

	--		--Get the current Id number for the details table
	--SELECT @lPurchaseOrderDetailCurrentId = CurrentNumber FROM sCommon.tTableRowId WHERE TableTitle = 'sProcurement.tPurchaseOrderDetail' AND OrgId = @rOrgId
	

	--INSERT INTO sProcurement.tPurchaseOrderDetail
	--	(
	--		Id, 
	--		PurchaseOrderId, 
	--		ItemSourceTypeId, 
	--		ItemSourceId, 
	--		StockItemPurchaseUomId, 
	--		OrderQuantity, 
	--		ReceivedOrderQuantity, 
	--		BonusQuantity, 
	--		NetUnitPrice, 
	--		TaxGroupId, 
	--		TaxRate, 
	--		TaxAmount, 
	--		OtherTaxAmount, 
	--		DiscountAmount, 
	--		DiscountPercentage, 
	--		RequestedDeliveryDate, 
	--		IsObsolete, 
	--		CreatedUserId, 
	--		CreatedDateTime, 
	--		UpdatedUserId, 
	--		UpdatedDateTime,
	--		OrgId
	--	)
	--SELECT  
	--	@lPurchaseOrderDetailCurrentId + ROW_NUMBER() OVER(ORDER BY ItemSourceId) AS Id, 
	--	@rPurchaseOrderId, 
	--	ItemSourceTypeId, 
	--	ItemSourceId, 
	--	PurchaseUomId, 
	--	OrderQuantity, 
	--	ReceivedOrderQuantity, 
	--	BonusQuantity, 
	--	NetUnitPrice, 
	--	(CASE WHEN TaxGroupId = 0 THEN NULL ELSE TaxGroupId END) TaxGroupId, 
	--	TaxRate, 
	--	TaxAmount, 
	--	OtherTaxAmount, 
	--	DiscountAmount, 
	--	DiscountPercentage, 
	--	RequestedDeliveryDate, 
	--	IsObsolete, 
	--	@rUpdatedUserId, 
	--	sCommon.fGetDate(), 
	--	@rUpdatedUserId, 
	--	sCommon.fGetDate(),
	--	@rOrgId
	--FROM OPENXML (@loIdoc, '/PurchaseOrder/PurchaseOrderDetail', 1)
	--	WITH ( 
	--			Id bigint, 
	--			ItemSourceTypeId INT, 
	--			ItemSourceId INT, 
	--			PurchaseUomId INT, 
	--			OrderQuantity  DECIMAL(22, 6), 
	--			ReceivedOrderQuantity DECIMAL(22, 6), 
	--			BonusQuantity DECIMAL(22, 6), 
	--			NetUnitPrice DECIMAL(22, 6), 
	--			TaxGroupId INT, 
	--			TaxRate DECIMAL(22, 6), 
	--			TaxAmount DECIMAL(22, 6), 
	--			OtherTaxAmount DECIMAL(22, 6), 
	--			DiscountAmount DECIMAL(22, 6), 
	--			DiscountPercentage DECIMAL(22, 6), 
	--			RequestedDeliveryDate SMALLDATETIME, 
	--			IsObsolete BIT
	--		  ) WHERE Id < 0 Order BY Id ASC
		
	--	SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/PurchaseOrder/PurchaseOrderDetail', 1)
	--			 WITH ( Id BIGINT, ItemSourceId INT) WHERE Id < 0
	--	SET @lPurchaseOrderDetailCurrentId  = @lCount + @lPurchaseOrderDetailCurrentId 
		
	--	EXECUTE sCommon.pTableRowIdModify @rOrgId = @rOrgId,  @rTableTitle = 'sProcurement.tPurchaseOrderDetail', @rCurrentNumber = @lPurchaseOrderDetailCurrentId 
	  
	  
	--  UPDATE sProcurement.tPurchaseOrderDetail
	--	SET ItemSourceTypeId = XmlTable.ItemSourceTypeId, 
	--		ItemSourceId = XmlTable.ItemSourceId, 
	--		StockItemPurchaseUomId = XmlTable.PurchaseUomId, 
	--		OrderQuantity = XmlTable.OrderQuantity, 
	--		ReceivedOrderQuantity = XmlTable.ReceivedOrderQuantity, 
	--		BonusQuantity = XmlTable.BonusQuantity, 
	--		NetUnitPrice = XmlTable.NetUnitPrice, 
	--		TaxGroupId = (CASE WHEN XmlTable.TaxGroupId = 0 THEN NULL ELSE XmlTable.TaxGroupId END), 
	--		TaxRate = XmlTable.TaxRate, 
	--		TaxAmount = XmlTable.TaxAmount, 
	--		OtherTaxAmount = XmlTable.OtherTaxAmount, 
	--		DiscountAmount = XmlTable.DiscountAmount, 
	--		DiscountPercentage = XmlTable.DiscountPercentage, 
	--		RequestedDeliveryDate = XmlTable.RequestedDeliveryDate, 
	--		IsObsolete = XmlTable.IsObsolete, 
	--		UpdatedUserId = @rUpdatedUserId, 
	--		UpdatedDateTime = sCommon.fGetDate()
	--	FROM OPENXML (@loIdoc, '/PurchaseOrder/PurchaseOrderDetail', 1)
	--			 WITH ( 
	--					Id bigint, 
	--					ItemSourceTypeId INT, 
	--					ItemSourceId INT, 
	--					PurchaseUomId INT, 
	--					OrderQuantity DECIMAL(22, 6), 
	--					ReceivedOrderQuantity DECIMAL(22, 6), 
	--					BonusQuantity DECIMAL(22, 6), 
	--					NetUnitPrice DECIMAL(22, 6), 
	--					TaxGroupId INT, 
	--					TaxRate DECIMAL(22, 6), 
	--					TaxAmount DECIMAL(22, 6), 
	--					OtherTaxAmount DECIMAL(22, 6), 
	--					DiscountAmount DECIMAL(22, 6), 
	--					DiscountPercentage DECIMAL(22, 6), 
	--					RequestedDeliveryDate SMALLDATETIME, 
	--					IsObsolete BIT
	--				  ) XmlTable
	--		INNER JOIN sProcurement.tPurchaseOrderDetail POD
	--			ON	POD.Id = XmlTable.Id 
	--		 WHERE XmlTable.Id > 0 
	
	SELECT 0 
END
GO
PRINT N'Altering Procedure [sProcurement].[pFirstAidEmployeeAdd]...';


GO
ALTER   PROCEDURE [sProcurement].[pFirstAidEmployeeAdd]
	 
	@rId bigint,
	@rIssueNumber nvarchar(20),
	@rFirstAidId int,
	@rStoreLocationId int,
	@rRemark nvarchar(300),
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgId smallint,
	@rIssueDate date,
	@rIssueBy nvarchar(150),
	@rEmployeeId bigint
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
	 
	 
-- IF(@rId = 0)	
--BEGIN

 
--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1008,@rStoreLocationId = @rStoreLocationId, @rNextNumber  = @rIssueNumber OUTPUT

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

--IF @rIssueNumber = '-300'
--BEGIN


--SELECT -300 AS Result, '' AS Number, 0 AS Id 
--RETURN

--END

	
--	 DECLARE @lNextNumber BIGINT     
--	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tFirstAidEmoloyee', 0, 1, 1 ,@outNextNumber = @lNextNumber output


--	INSERT INTO sProcurement.tFirstAidEmoloyee
--		(
--			Id,
--			Number,
--			FirstAidId,
--			StoreLocationId,
--			Remark,
--			CreatedUserId,
--			CreatedDateTime,
--			OrgId,
--			IssueDate,
--			IssueBy,
--			EmployeeId
--		)
--	VALUES
--		(
--			@lNextNumber,
--			@rIssueNumber, 
--			@rFirstAidId,
--			@rStoreLocationId ,
--			@rRemark ,
--			@rCreatedUserId ,
--			sCommon.fGetDate(),
--			@rOrgId,
--			@rIssueDate,
--			@rIssueBy,
--			@rEmployeeId
--		)
		             
--	END	 
 
--	 ELSE
--	 BEGIN
--	 SET @lNextNumber = @rId
--	    UPDATE  sProcurement.tFirstAidEmoloyee
--	    SET
--			Number=@rIssueNumber,
--			FirstAidId=@rFirstAidId,
--			StoreLocationId=@rStoreLocationId,
--			Remark=@rRemark,
--			UpdatedUserId=@rUpdatedUserId,
--			UpdatedDateTime=sCommon.fGetDate(),
--			OrgId=@rOrgId,
--			IssueDate=@rIssueDate,
--			IssueBy=@rIssueBy,
--			EmployeeId=@rEmployeeId
			
--		WHERE Id = @rId 
	      	   
--	 END  
	 
	 
--	 SELECT 1 AS Result, @rIssueNumber AS Number, @lNextNumber AS Id 
--		SELECT @lNextNumber AS Result
	
--		--COMMIT TRANSACTION
		
--	--END TRY
	
--	--BEGIN CATCH 
--	--	ROLLBACK TRANSACTION
--	--	SELECT -1 AS Result
--	--END CATCH	

SELECT 0 AS Result,0 AS Number, 0 AS Id 
		
END
GO
PRINT N'Altering Procedure [sProcurement].[pFirstAidInspectionAdd]...';


GO
ALTER   PROCEDURE [sProcurement].[pFirstAidInspectionAdd]
	 
	@rId bigint,
	@rInspectionNumber nvarchar(20),
	@rEmployeeId bigint,
	@rStoreLocationId int,
	@rRemark nvarchar(300),
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgId smallint,
	@rInspectionDate date
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
--	--BEGIN TRY
	
--	-- BEGIN TRANSACTION	
	 
	 
-- IF(@rId = 0)	
--BEGIN

 
--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1009,@rStoreLocationId = @rStoreLocationId, @rNextNumber  = @rInspectionNumber OUTPUT

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

--IF @rInspectionNumber = '-300'
--BEGIN


--SELECT -300 AS Result, '' AS Number, 0 AS Id 
--RETURN

--END

	
--	 DECLARE @lNextNumber BIGINT     
--	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tFirstAidInspection', 0, 1, 1 ,@outNextNumber = @lNextNumber output


--	INSERT INTO sProcurement.tFirstAidInspection
--		(
--			Id,
--			Number,
--			EmployeeId,
--			StoreLocationId,
--			Remark,
--			CreatedUserId,
--			CreatedDateTime,
--			OrgId,
--			InspectionDate
		
--		)
--	VALUES
--		(
--			@lNextNumber,
--			@rInspectionNumber, 
--			@rEmployeeId,
--			@rStoreLocationId ,
--			@rRemark ,
--			@rCreatedUserId ,
--			sCommon.fGetDate(),
--			@rOrgId,
--			@rInspectionDate
		
--		)
		             
--	END	 
 
--	 ELSE
--	 BEGIN
--	 SET @lNextNumber = @rId
--	    UPDATE  sProcurement.tFirstAidInspection
--	    SET
--			Number=@rInspectionNumber,
--			EmployeeId=@rEmployeeId,
--			StoreLocationId=@rStoreLocationId,
--			Remark=@rRemark,
--			UpdatedUserId=@rUpdatedUserId,
--			UpdatedDateTime=sCommon.fGetDate(),
--			OrgId=@rOrgId,
--			InspectionDate=@rInspectionDate
		
--		WHERE Id = @rId 
	      	   
--	 END  
	 
	 
--	 SELECT 1 AS Result, @rInspectionNumber AS Number, @lNextNumber AS Id 
--		--SELECT @lNextNumber AS Result
	
--		--COMMIT TRANSACTION
		
--	--END TRY
	
--	--BEGIN CATCH 
--	--	ROLLBACK TRANSACTION
--	--	SELECT -1 AS Result
--	--END CATCH	
		
		SELECT 0 AS Result, 0 AS Number, 0 AS Id 
END
GO
PRINT N'Altering Procedure [sCommunication].[pAssignmentListGet]...';


GO
ALTER PROCEDURE [sCommunication].[pAssignmentListGet] 
	@rBatchId INT
	,@rUserId BIGINT
	,@rUserSourceId BIGINT
	,@rUserSourceTypeId INT
	,@rSyncedAssignmentId BIGINT = 0
	,@rName NVARCHAR(100) = ''
	,@rFromDate DATE = ''
	,@rToDate DATE = ''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lOrgGroupBatchId INT = 0

	SELECT @lOrgGroupBatchId = OrgGroupBatchId
	FROM sSetup.tBatchMaster
	WHERE Id = @rBatchId

	--DECLARE @lDivisionId int
	--SELECT @lDivisionId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
	DECLARE @lConfigValue NVARCHAR(50)
	DECLARE @lIsAssignmentBasedOnApproval BIT = 0

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

	IF (@lConfigValue IS NULL)
		OR (@lConfigValue = 'False')
		SET @lIsAssignmentBasedOnApproval = 0
	ELSE
		SET @lIsAssignmentBasedOnApproval = 1

	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END

	IF @rUserSourceTypeId = 2003 -- For Student Login
	BEGIN
		IF OBJECT_ID(N'tempdb..#DivisionData') IS NOT NULL
		BEGIN
			DROP TABLE #DivisionData
		END

		SELECT A.DivisionId, DM.ClassId
		INTO #DivisionData
		FROM sStudent.tAcademic A
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId --Added for mantis : 42198
		WHERE A.StudentId = @rUserSourceId AND A.BatchId = @rBatchId
		

		;WITH AssignmentBase AS (
			SELECT A1.Id AS AssignmentId,
				   A1.SubjectId,
				   SM.Title AS SubjectName,
				   A1.Title,
				   A1.Remark,
				   A1.StartDate,
				   A1.EndDate,
				   --0 AS UserId,
				   --(SELECT Userid FROM sCommunication.tAssignmentView  WHERE AssignmentId = A1.Id AND UserId = @rUserId) AS UserId,
				   ISNULL(AV.UserId, 0) AS UserId,
				   U.DisplayTitle AS CreatedUserName,
				   SM.OrgId,
				   ISNULL(A1.IsAssignmentDocumentUpload, 0) AS IsAssignmentDocumentUpload,
				   A1.CreatedDateTime,
				   CS.IsOptional,
				   CS.Id AS ClassSubjectId,
				   AS1.SourceId
				   ,CS.ClassId --MantisId:0045284
			FROM sCommunication.tAssignment A1
			INNER JOIN sCommunication.tAssignmentScope AS1 ON AS1.AssignmentId = A1.Id
			INNER JOIN #DivisionData D ON D.DivisionId = AS1.SourceId AND AS1.SourceTypeId = 2005
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = A1.SubjectId
			INNER JOIN sSetup.tClassSubject CS ON CS.SubjectId = A1.SubjectId AND D.ClassId = CS.ClassId
			INNER JOIN sSecurity.tUser U ON U.Id = A1.CreatedUserId
			LEFT JOIN sCommunication.tAssignmentView AV ON AV.AssignmentId = A1.Id AND UserId = @rUserId
			WHERE A1.BatchId = @rBatchId
			AND (
				A1.Id > @rSyncedAssignmentId
				OR @rSyncedAssignmentId = 0
				)
			AND (CAST(A1.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)
				--Convert(DATE, A1.CreatedDateTime) >= convert(DATE, @rFromDate)
				OR ISNULL(@rFromDate, '') = ''
				)
			AND (
				CAST(A1.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)
				--Convert(DATE, A1.CreatedDateTime) <= convert(DATE, @rToDate)
				OR ISNULL(@rToDate, '') = ''
				)
			AND (
				A1.Title LIKE @rName
				OR ISNULL(@rName, '') = ''
				)
			AND (
				(@lIsAssignmentBasedOnApproval = 0)
				OR (
					@lIsAssignmentBasedOnApproval = 1
					AND A1.StatusId = 550
					)
				)
		)
		SELECT AB.AssignmentId, AB.SubjectId, AB.SubjectName, AB.Title, AB.Remark,
			   AB.StartDate, AB.EndDate, AB.UserId, AB.CreatedUserName, AB.OrgId, AB.IsAssignmentDocumentUpload
		FROM AssignmentBase AB
		WHERE AB.IsOptional = 0

		UNION

		SELECT AB.AssignmentId, AB.SubjectId, AB.SubjectName, AB.Title, AB.Remark,
			   AB.StartDate, AB.EndDate, AB.UserId, AB.CreatedUserName, AB.OrgId, AB.IsAssignmentDocumentUpload
		FROM AssignmentBase AB
		INNER JOIN sAssessment.tOptionalSubject OS ON OS.ClassSubjectId = AB.ClassSubjectId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = OS.AcademicId
										  AND SA.DivisionId = AB.SourceId
										  AND SA.ClassId = AB.ClassId --MantisId:0045284
		WHERE AB.IsOptional = 1 AND SA.StudentId = @rUserSourceId

		--SELECT A1.Id AS AssignmentId
		--	,A1.SubjectId
		--	,SM.Title AS SubjectName
		--	,A1.Title
		--	,A1.Remark
		--	,A1.StartDate
		--	,A1.EndDate
		--	,ISNULL(AV.UserId, 0) AS UserId
		--	,U.DisplayTitle AS CreatedUserName
		--	,SM.OrgId
		--	,ISNULL(A1.IsAssignmentDocumentUpload, 0) AS IsAssignmentDocumentUpload
		--FROM sCommunication.tAssignment A1
		--INNER JOIN sCommunication.tAssignmentScope AS1 ON AS1.AssignmentId = A1.Id
		--INNER JOIN #DivisionData D ON D.DivisionId = AS1.SourceId AND AS1.SourceTypeId = 2005
		----INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AS1.SourceId --Added for mantis : 42198
		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = A1.SubjectId
		--INNER JOIN [sSetup].[tClassSubject] CS ON CS.SubjectId = A1.SubjectId AND D.ClassId = CS.ClassId --Added for mantis : 42198
		--INNER JOIN sSecurity.tUser U ON U.Id = A1.CreatedUserId
		--LEFT JOIN sCommunication.tAssignmentView AV ON AV.AssignmentId = A1.Id AND UserId = @rUserId
		--WHERE CS.IsOptional = 0 --Added for mantis : 42198
		--	AND A1.BatchId = @rBatchId
		--	AND (
		--		A1.Id > @rSyncedAssignmentId
		--		OR @rSyncedAssignmentId = 0
		--		)
		--	AND (
		--		Convert(DATE, A1.CreatedDateTime) >= convert(DATE, @rFromDate)
		--		OR ISNULL(@rFromDate, '') = ''
		--		)
		--	AND (
		--		Convert(DATE, A1.CreatedDateTime) <= convert(DATE, @rToDate)
		--		OR ISNULL(@rToDate, '') = ''
		--		)
		--	AND (
		--		A1.Title LIKE @rName
		--		OR ISNULL(@rName, '') = ''
		--		)
		--	AND (
		--		(@lIsAssignmentBasedOnApproval = 0)
		--		OR (
		--			@lIsAssignmentBasedOnApproval = 1
		--			AND A1.StatusId = 550
		--			)
		--		)
		----Order by A1.CreatedDateTime DESC 
		
		--UNION
		
		----Added this query for mantis : 42198
		--SELECT A1.Id AS AssignmentId
		--	,A1.SubjectId
		--	,SM.Title AS SubjectName
		--	,A1.Title
		--	,A1.Remark
		--	,A1.StartDate
		--	,A1.EndDate
		--	,ISNULL(AV.UserId, 0) AS UserId
		--	,U.DisplayTitle AS CreatedUserName
		--	,SM.OrgId
		--	,ISNULL(A1.IsAssignmentDocumentUpload, 0) AS IsAssignmentDocumentUpload
		--FROM sCommunication.tAssignment A1
		--INNER JOIN sCommunication.tAssignmentScope AS1 ON AS1.AssignmentId = A1.Id
		--INNER JOIN  #DivisionData D ON D.DivisionId = AS1.SourceId AND AS1.SourceTypeId = 2005
		----(
		----	SELECT A.DivisionId
		----	FROM sStudent.tAcademic A
		----	WHERE A.StudentId = @rUserSourceId
		----		AND A.BatchId = @rBatchId
		----	) D ON D.DivisionId = AS1.SourceId
		----INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AS1.SourceId 
		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = A1.SubjectId
		--INNER JOIN [sSetup].[tClassSubject] CS ON CS.SubjectId = A1.SubjectId AND D.ClassId = CS.ClassId
		--INNER JOIN [sAssessment].[tOptionalSubject] AS OS ON OS.ClassSubjectId = CS.Id
		--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = OS.AcademicId AND CS.ClassId = SA.ClassId AND SA.DivisionId = AS1.SourceId
		--INNER JOIN sSecurity.tUser U ON U.Id = A1.CreatedUserId
		--LEFT JOIN sCommunication.tAssignmentView AV ON AV.AssignmentId = A1.Id AND UserId = @rUserId
		--WHERE CS.IsOptional = 1
		--	AND SA.StudentId = @rUserSourceId
		--	AND A1.BatchId = @rBatchId
		--	AND (
		--		A1.Id > @rSyncedAssignmentId
		--		OR @rSyncedAssignmentId = 0
		--		)
		--	AND (
		--		Convert(DATE, A1.CreatedDateTime) >= convert(DATE, @rFromDate)
		--		OR ISNULL(@rFromDate, '') = ''
		--		)
		--	AND (
		--		Convert(DATE, A1.CreatedDateTime) <= convert(DATE, @rToDate)
		--		OR ISNULL(@rToDate, '') = ''
		--		)
		--	AND (
		--		A1.Title LIKE @rName
		--		OR ISNULL(@rName, '') = ''
		--		)
		--	AND (
		--		(@lIsAssignmentBasedOnApproval = 0)
		--		OR (
		--			@lIsAssignmentBasedOnApproval = 1
		--			AND A1.StatusId = 550
		--			)
		--		)
		--	--Order by A1.CreatedDateTime DESC 
	END
	ELSE
	BEGIN
		--IF @rUserSourceTypeId   = 2003 -- For Student Login
		SELECT A1.Id AS AssignmentId
			,A1.SubjectId
			,SM.Title AS SubjectName
			,A1.Title
			,A1.Remark
			,A1.StartDate
			,A1.EndDate
			,ISNULL(AV.UserId, 0) AS UserId
			,U.DisplayTitle AS CreatedUserName
			,SM.OrgId
			,ISNULL(A1.IsAssignmentDocumentUpload, 0) AS IsAssignmentDocumentUpload
		FROM sCommunication.tAssignment A1
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = A1.SubjectId
		LEFT JOIN sCommunication.tAssignmentView AV ON AV.AssignmentId = A1.Id
			AND UserId = @rUserId
		INNER JOIN sCommunication.tAssignmentScope AS1 ON AS1.AssignmentId = A1.Id
		INNER JOIN (
			SELECT EJD.OrganizationDepartmentId
			FROM sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			WHERE EM.Id = @rUserSourceId
				AND ISNULL(EM.IsOtherUser, 0) = 0
			) D ON D.OrganizationDepartmentId = AS1.SourceId
			AND AS1.SourceTypeId = 2017
		INNER JOIN sSecurity.tUser U ON U.Id = A1.CreatedUserId
		WHERE A1.BatchId = @rBatchId
			AND (
				A1.Id > @rSyncedAssignmentId
				OR @rSyncedAssignmentId = 0
				)
			AND (
				Convert(DATE, A1.CreatedDateTime) >= convert(DATE, @rFromDate)
				OR ISNULL(@rFromDate, '') = ''
				)
			AND (
				Convert(DATE, A1.CreatedDateTime) <= convert(DATE, @rToDate)
				OR ISNULL(@rToDate, '') = ''
				)
			AND (
				A1.Title LIKE @rName
				OR ISNULL(@rName, '') = ''
				)
		ORDER BY A1.CreatedDateTime DESC
	END
END
GO
PRINT N'Altering Procedure [sCommunication].[pMyUpdateGet]...';


GO

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

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

	IF EXISTS(SELECT * FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId AND DeviceToken = @rDeviceToken)
	BEGIN
		DECLARE @lDeviceDetail nvarchar(max)='' ,@lCount int,@lDeletedCount int
		SELECT @lCount = COUNT(*) FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId AND DeviceToken = @rDeviceToken
		SELECT @lDeletedCount = COUNT(*) FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId AND DeviceToken = @rDeviceToken AND LOWER(DeviceDetail) LIKE '%deleted%'
		
		IF(@lCount = @lDeletedCount)
		BEGIN
			--SELECT @lDeviceDetail = DeviceDetail FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId AND DeviceToken = @rDeviceToken

			--IF LOWER(@lDeviceDetail) = 'deleted'
			--BEGIN
				SET @lIsActive=0
			--END
			
		END
		
	END
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT * FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId AND DeviceToken = @rDeviceToken)
		BEGIN
			INSERT INTO [sCommunication].[tRegisteredUsers]
			   (OrgId
			   ,UserId
			   ,UserSourceId
			   ,UserSourceTypeId
			   ,DeviceToken
			   ,OSTypeId
			   ,CreatedDateTime
			   ,AppVersion
			   ,AppName
			   ,DeviceDetail)
		 VALUES
			   (@rOrgId
			   ,@rUserId
			   ,@rUserSourceId
			   ,@rUserSourceTypeId
			   ,@rDeviceToken
			   ,2
			   ,sCommon.fGetDate()
			   ,@rAppVersion
			   ,@rAppName
			   ,@rVersionNumber)
		END
	END
END
--IF(@rOSTypeId = 2)
--BEGIN
--	 DECLARE @lOldDeviceToken nvarchar(200)=''
--	 SELECT TOP 1 @lOldDeviceToken = DeviceToken FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId  AND CHARINDEX(':', DeviceToken) = 0
--	 IF(@lDeviceToken!=@rDeviceToken AND CHARINDEX(':', @lDeviceToken) = 0)  
--	 BEGIN
--			IF(LEN(@rDeviceToken) > 0)  
--			BEGIN
--				UPDATE sCommunication.tRegisteredUsers SET DeviceToken = @rDeviceToken WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId  
--				SET @lIsActive=1
--			END
--	 END
--	 --ELSE
--	 --BEGIN
--	 --if
--		----SET @lIsActive=1
--	 --END
--END
--END

 SET @lDeviceToken = (SELECT DeviceToken FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND DeviceToken=@rDeviceToken)  	
 IF(@lDeviceToken IS NULL OR @lDeviceToken='' OR ISNULL(@lDeviceToken,'') = '')  
  SET @lIsActive=0  
END  
  
DECLARE @lActiceClassBatchId NVARCHAR(MAX) = '',@lBatchClassId int  
   
IF(@rUserSourceTypeId = 2003)  
BEGIN   
 SELECT @lBatchClassId = A.ClassId  
 FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id  
 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId  
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
  
 IF EXISTS(SELECT BatchId FROM [sSetup].[tBatchClass] BC INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BC.BatchId WHERE ClassId = @lBatchClassId AND IsBatchClassActive = 1 AND BM.IsActive = 1)  
 BEGIN  
  SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,BC.BatchId)+','+ BM.Title FROM [sSetup].[tBatchClass] BC INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BC.BatchId WHERE BC.ClassId = @lBatchClassId AND BC.IsBatchClassActive = 1 AND BM.IsActive = 1  
 END  
 ELSE  
 BEGIN  
  SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,Id) +','+ Title FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
 END  
END  
ELSE IF(@rUserSourceTypeId = 95)  
BEGIN  
 SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,Id) +','+ Title FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
END  


IF(LEN(ISNULL(@rAppVersion,'')) > 0 AND LEN(ISNULL(@rAppVersion,'')) > 0)
BEGIN
	UPDATE sCommunication.tRegisteredUsers
	SET
		AppVersion = @rAppVersion,
		AppName = @rAppName,
		UpdatedDateTime = sCommon.fGetDate(),
		DeviceDetail = @rVersionNumber
	WHERE 
		DeviceToken = @rDeviceToken 
		AND OsTypeId = @rOSTypeId
		AND OrgId=@rOrgId AND UserId=@rUserId 
		AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId
END

-- Mantis - 45150 - For Vedant Check Version and Add Entry New Device Token if Not Match with Old Token
IF(@rAppVersion='6.0.50' AND @lOrgGroupId=1996 AND @rOSTypeId=1)
BEGIN
	IF NOT EXISTS(SELECT * FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId AND DeviceToken = @rDeviceToken)
			BEGIN
				INSERT INTO [sCommunication].[tRegisteredUsers]
				   (OrgId
				   ,UserId
				   ,UserSourceId
				   ,UserSourceTypeId
				   ,DeviceToken
				   ,OSTypeId
				   ,CreatedDateTime
				   ,AppVersion
				   ,AppName
				   ,DeviceDetail)
			 VALUES
				   (@rOrgId
				   ,@rUserId
				   ,@rUserSourceId
				   ,@rUserSourceTypeId
				   ,@rDeviceToken
				   ,1
				   ,sCommon.fGetDate()
				   ,@rAppVersion
				   ,@rAppName
				   ,@rVersionNumber)
			END

			Set @lIsActive = 1
END


CREATE TABLE #Module (  
Id int,  
Title nvarchar(2000),  
IsNew bit )  

--IF(@rAppVersion <> '5.8.1')
--BEGIN
INSERT INTO #Module VALUES (1,'IsActiveCheck',CONVERT(bit,@lIsActive))  
INSERT INTO #Module VALUES (2,'IsOptimizeAppImageUpload',@lIsOptimizeAppImageUpload)  
INSERT INTO #Module VALUES (3,ISNULL(@lAlertRemark,''),1)  
INSERT INTO #Module VALUES (4,ISNULL(@lMobileAppModuleAutoSyncToken,0),1)  
INSERT INTO #Module VALUES (5,'Is Stop Application Access',@lIsStopApplicationAccess)  
INSERT INTO #Module VALUES (6,@lStudentCustomAlert,1)  
INSERT INTO #Module VALUES (20085,'Circular',0)  
INSERT INTO #Module VALUES (20088,'Query',0)  
INSERT INTO #Module VALUES (20099,'Blog',0)  
INSERT INTO #Module VALUES (20104,'News',0)  
INSERT INTO #Module VALUES (20172,'AssignTask',0)  
INSERT INTO #Module VALUES (20183,'Gallery',0)  
INSERT INTO #Module VALUES (20204,'Poll',0)  
INSERT INTO #Module VALUES (20093,'Assignment',0)  
INSERT INTO #Module VALUES (20209,'Activity',0)  
INSERT INTO #Module VALUES (20130,'Behaviour',0)  
INSERT INTO #Module VALUES (20180,'Result',0)  
INSERT INTO #Module VALUES (7,@lActiceClassBatchId,1)  
--END
--ELSE
--BEGIN
--INSERT INTO #Module VALUES (null,null,null)
--END
   
SELECT * FROM #Module  
   
--SELECT @lAssignmentStatus AS Assignment,@lCircularStatus AS Circular,@lPollStatus AS Poll,@lQueryStatus AS Query,  
--@lBlogStatus AS Blog,@lNewsStatus AS News,@lBehaviourStatus AS Behaviour,  
--@lActivityStatus AS Activity,@lResultStatus AS Result,@lAssignTaskStatus AS AssignTask,@lPhotoCategoryStatus AS Gallery  
  
END
GO
PRINT N'Altering Procedure [sEExam].[pAutoGenerateQuestionAdd]...';


GO
ALTER   PROCEDURE [sEExam].[pAutoGenerateQuestionAdd]
	
	@rTopicId nvarchar(max),
	@rDifficultyLevelId tinyint,	 
	@rNoOfQuestions int,	 
	@rTestId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 0 AS Result
	--Commented on 19/06/2025 - Column name or number of supplied values does not match table definition.	
	--DECLARE @1Count Int,
 --   @1QuestionId bigint,
 --   @1Marks decimal(6,2) 
	
	--CREATE Table #temp
	--(
	--	Id int IDENTITY(1,1) not null,
	--	QuestionId bigint not null,
	--	Marks  Decimal(6,2)
	--)
	
	--Insert Into #temp 
	--select Id,Marks from sEExam.tQuestionMaster Where TopicId IN (select * from [sCommon].[fnSplit](@rTopicId,',')) AND DifficultyLevelId = @rDifficultyLevelId  
	--Order By RAND(Id) 
	
	--Select @1Count = count(*) from #temp
	-- IF(@1Count > @rNoOfQuestions)
	--  BEGIN
	--     SET @1Count = @rNoOfQuestions
	--  END
	
	--While (@1Count > 0)
	--  BEGIN	  
	--        SELECT @1QuestionId = QuestionId,@1Marks = Marks From #temp Where Id = @1Count 
	        
	--        IF NOT EXISTS(Select 1 FROM sEExam.tTestQuestion Where TestId = @rTestId 
	--        AND QuestionId = @1QuestionId) 
	--         BEGIN
	--            INSERT INTO sEExam.tTestQuestion
	--            SELECT @rTestId,@1QuestionId,@1Marks
	--         END   
	--  END		
END
GO
PRINT N'Altering Procedure [sEExam].[pQuestionParagraphGet]...';


GO
ALTER   PROCEDURE [sEExam].[pQuestionParagraphGet]
 
		@rParagraphId bigint,
		@rOrgId int

 
 AS
 
 BEGIN 
	SELECT   '' AS QuestionParagraphDescription2
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
        --SELECT   
        --     QuestionParagraphDescription2
        --FROM 
        --sEExam.tQuestionParagraph QP
        
        --Where Id = @rParagraphId  AND OrgId = @rOrgId
       
 END
GO
PRINT N'Altering Procedure [sFee].[pExportFeeReceiptDeletedLog]...';


GO
ALTER PROCEDURE [sFee].[pExportFeeReceiptDeletedLog]

	 @rOrgGroupBatchId bigint,
	 @rOrgId bigint=0,
	 @rFromDate date=NULL,
	 @rToDate date=NULL
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		SELECT 
			R.Code,
			R.SourceName,
			R.ReceiptNumber,			
			convert(varchar(10), R.ReceiptDate, 103) As ReceiptDate,
			R.ReceiptAmount,
			R.PayType,
			R.ChequeNo,
			R.BankName,
			R.ReceiptBookName,
			R.Remark,
			R.CreatedUser,				
            convert(varchar(10),R.CreatedDateTime, 103) + right(convert(varchar(32),R.CreatedDateTime,100),8) As CreatedDateTime,	 		
			R.CollectionGroupName,
			R.DeletededUser,			
			convert(varchar(10),R.DeletedDateTime, 103) + right(convert(varchar(32),R.DeletedDateTime,100),8) As DeletedDateTime,	 
			(SELECT DISTINCT
			 STUFF((SELECT ',' + U.FeeName + '-' + CONVERT(varchar(20), U.Amount)		-- changed nvarchar(10) to (20) 03-04-2025 by Rahul
					FROM sAudit.tReceiptDetailDelete U
					WHERE U.FeeName = FeeName And  ReceiptId=R.Id
					ORDER BY U.FeeName FOR XML PATH('')),1,1,''
					) AS ReceiptDetailDeletelist
		     FROM sAudit.tReceiptDetailDelete GROUP BY ReceiptId
		     ) AS DeletedReceiptDetail
			 ,CASE WHEN RD.ID IS NULL THEN 'Cancel' ELSE 'Delete' END AS ReceiptStatus --Added for Mantis Id: 0045048
		FROM 
		   sAudit.tReceiptDelete R
		   INNER JOIN sStudent.vStudentAcademic SA ON R.SourceId=SA.AcademicId
		   LEFT JOIN [sFee].[tReceiptDeleted] RD ON RD.Id = R.Id --Added for Mantis Id: 0045048
		WHERE 
		   SA.OrgGroupBatchId =@rOrgGroupBatchId
		   AND ((SA.OrgId=@rOrgId) OR (@rOrgId = 0))
		   AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		   AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		ORDER BY R.ReceiptDate DESC    
END
GO
PRINT N'Altering Procedure [sFee].[pRptPostDatedPaymentGet]...';


GO


ALTER PROCEDURE [sFee].[pRptPostDatedPaymentGet]
	@rOrgGroupBatchId int = 0,
	@rOrgId int = 0,
	@rBatchId int = 0,
	@rSourceId bigint =0,
	@rSourceTypeId smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 		
	SELECT DISTINCT 	 
		 PDP.Id
		,PDP.OrgId
		,ISNULL(OM.Title, '') AS Organization
		,PDP.BatchId
		,ISNULL(BM.Title, '') AS Batch
		,ISNULL(SA.Code, '') AS IdNo
		,ISNULL(SA.ClassName, '') + ' - ' + ISNULL(SA.DivisionName, '') AS ClassDivision
		,ISNULL(SA.Name, '') AS StudentName
		,PDP.OrgGroupBatchId
		,PDP.SourceTypeId
		,PDP.SourceId
		,ISNULL(PDP.ReceiptId, 0) AS ReceiptId
		,PDP.ReceiptBookId
		,PDP.PayTypeId
		,PDP.PaymentClearanceDate
		,PDP.ChequeNo
		,PDP.BankName
		,PDP.Amount AS ReceiptAmount
		,ISNULL(PDP.Remark, '') AS Remark
		,PDP.CreatedUserId
		,PDP.CreatedDateTime
		,PDP.UpdatedUserId
		,PDP.UpdatedDateTime
		,PDP.StatusId
		,ISNULL(R.ReceiptNumber, '') AS ReceiptNumber
		,ISNULL(RBM.Title, '') AS ReceiptBookTitle
		,ISNULL(PDP.ReceiptDate, '') AS ReceiptDate
		,ISNULL(PTM.Title, '') AS PayType
        ,ISNULL(SM.Title, '') AS StatusTitle
		,CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId
		,RBM.ReceiptBookHeader
		,OM.OrgLogo
		,ISNULL(RBM.GroupTitle,'') AS GroupTitle
		,ISNULL(RBM.FullTitle,'') AS FullTitle
		,ISNULL(RBM.Address1,'') AS Address1
		,ISNULL(RBM.Address2,'') AS Address2
		,SA.RollNo
		,ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted

	FROM
		sFee.tPostDatePayment PDP
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = PDP.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = PDP.BatchId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = PDP.SourceId AND PDP.SourceTypeId = 2001
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PDP.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = PDP.ReceiptBookId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id = PDP.StatusId
		LEFT JOIN sFee.tReceipt R ON R.Id = PDP.ReceiptId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = RBM.Id
	WHERE
		(PDP.OrgId = @rOrgId OR @rOrgId = 0)
		AND (PDP.BatchId = @rBatchId OR @rBatchId = 0)
		AND (PDP.SourceId = @rSourceId OR @rSourceId = 0)
		AND (PDP.SourceTypeId = @rSourceTypeId OR @rSourceTypeId = 0)
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeDataUpdatetoUppperCase]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeDataUpdatetoUppperCase]
	@rId int
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	IF(@rId = 1)
	BEGIN
		UPDATE sHrm.tEmployeeMaster SET FirstName = UPPER(FirstName), MiddleName = UPPER(MiddleName)
			, LastName = UPPER(LastName), ShortName = UPPER(ShortName)
	END

	IF(@rId = 2)
	BEGIN
		UPDATE sHrm.tEmployeeJobDetail SET JobRemark = UPPER(JobRemark), ReasonOfleaving = UPPER(ReasonOfleaving)
			,ReferenceRemark = UPPER(ReferenceRemark), Subjects = UPPER(Subjects)
	END

	IF(@rId = 3)
	BEGIN
		UPDATE [sHrm].[tEmployeePersonalDetail] SET IdentificationMark1 = UPPER(IdentificationMark1), Qualification = UPPER(Qualification)
			,FamilyCast = UPPER(FamilyCast)
	END

	IF(@rId = 4)
	BEGIN
		UPDATE [sHrm].[tEmployeeCommunications] SET PresentStreetOne = UPPER(PresentStreetOne), PresentStreetTwo = UPPER(PresentStreetTwo)
			,PresentStreetThree = UPPER(PresentStreetThree), PresentCountry = UPPER(PresentCountry), PresentState = UPPER(PresentState)
			,PermanentStreetOne = UPPER(PermanentStreetOne), PresentCity = UPPER(PresentCity), PresentZipCode = UPPER(PresentZipCode)
			,PresentContactNo = UPPER(PresentContactNo), PermanentStreetTwo = UPPER(PermanentStreetTwo), PermanentStreetThree = UPPER(PermanentStreetThree)
			,PermanentCountry = UPPER(PermanentCountry), PermanentState = UPPER(PermanentState), PermanentCity = UPPER(PermanentCity) 
			,PermanentZipCode = UPPER(PermanentZipCode), PermanentContactNo = UPPER(PermanentContactNo), EmergencyStreetOne = UPPER(EmergencyStreetOne)
			,EmergencyStreetTwo = UPPER(EmergencyStreetTwo), EmergencyStreetThree = UPPER(EmergencyStreetThree), EmergencyCountry = UPPER(EmergencyCountry)
			,EmergencyState = UPPER(EmergencyState), EmergencyCity = UPPER(EmergencyCity), EmergencyZipCode = UPPER(EmergencyZipCode)
			,EmergencyContactNo = UPPER(EmergencyContactNo), CompanyEmail = UPPER(CompanyEmail), PersonalEmail = UPPER(PersonalEmail)
			,PhoneNoCompany = UPPER(PhoneNoCompany), ExtensionNo = UPPER(ExtensionNo), MobileNumber = UPPER(MobileNumber)
			,WhatsAppContactNo = UPPER(WhatsAppContactNo)
	END

	IF(@rId = 5)
	BEGIN
		UPDATE [sHrm].[tEmployeeStatutoryAndOther] SET EPFNumber = UPPER(EPFNumber), ESINumber = UPPER(ESINumber)
			,BankName = UPPER(BankName), Branch = UPPER(Branch), IFSCNumber = UPPER(IFSCNumber)
			,AccountHolderName = UPPER(AccountHolderName)
	END
     
	IF(@rId = 6)
	BEGIN
		UPDATE [sHrm].[tEmployeePreviousEmployment] SET CompanyName = UPPER(CompanyName), Designation = UPPER(Designation)
			,Duration = UPPER(Duration), Remark = UPPER(Remark), ReasonForLeaving = UPPER(ReasonForLeaving)
			,JobDescription = UPPER(JobDescription)
	END

	IF(@rId=7)
	BEGIN
		UPDATE [sHrm].[tEmployeeQualification] SET ExamPassed = UPPER(ExamPassed), PassYear = UPPER(PassYear)
		,Grade = UPPER(Grade), InstituteDetail = UPPER(InstituteDetail), BoardDetail = UPPER(BoardDetail)
		,Subjects = UPPER(Subjects), Remark = UPPER(Remark)
	END

	IF(@rId = 8)
	BEGIN
	UPDATE [sHrm].[tEmployeeFamilyDetails] SET Name = UPPER(Name),Occupation = UPPER(Occupation)
	,EmailId = UPPER(EmailId)
	END

END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeSearchGet]...';


GO
ALTER   PROCEDURE [sHrm].[pEmployeeSearchGet]
	 
	@rCode nvarchar(20),
	@rBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	
	--Commented on 19/06/2025 - Invalid column name 'Id'.
	--SELECT 
	--		VEM.Code,
	--		EB.Id AS EmployeeBatchId,
	--		VEM.Id AS EmployeeId,
	--		VEM.EmployeeName AS Name,
	--		VEM.DepartmentName,
	--		VEM.DepartmentId
 -- FROM 
	--	  sHrm.tEmployeeBatch EB
	--   INNER JOIN sHrm.vExtEmployeeMaster VEM ON VEM.Id=EB.EmployeeId
 -- WHERE 
	--		((VEM.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
	--	AND (EB.BatchId=@rBatchId)

	SELECT 
		'' AS Code,
		0 AS EmployeeBatchId,
		0 AS EmployeeId,
		0 AS Name,
		0 AS DepartmentName,
		0 AS DepartmentId
END
GO
PRINT N'Altering Procedure [sHrm].[pRptLeaveDeductionGet]...';


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

       SELECT 			
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			@rIsDetail AS IsDetail,
			@rIsOpeningLeave AS IsOpeningLeave,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,   
			EM.EmployeeId,
			EM.DepartmentName,
			EM.EmployeeGrade,      
			ISNULL(LB.BalanceLeave,0) AS BalanceLeave,
			LTM.Id AS LeaveTypeId,	
			LTM.Title AS LeaveType,
			ISNULL((SELECT TOP 1 LBL.BalanceLeave  FROM sHrm.tLeaveBalanceLog LBL			 
			WHERE LBL.EmployeeId = EM.EmployeeId 
			AND LBL.LeaveTypeId=LTM.Id 
			AND LBL.BatchId = @rBatchId 
			AND LBL.BalanceLeave!=0 
			AND LBL.LeaveTransactionId=2 
			ORDER BY LBL.CreatedDateTime ASC),0) AS FirstBalanceLeave,			
			--(
			--	SELECT ISNULL(SUM(L.NoOfLeave),0)				 
			--	FROM 
			--		sHrm.tLeave L
			--		INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
			--		AND IsLWP = 0 AND StatusId=550
			--	WHERE 
			--		L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
			--		AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
			--		AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
			--		AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
			--		AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
   -- 				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		 --  	) AS NoOfLeave,
	  -- 		(
			--SELECT ISNULL(SUM(L.NoOfLeave),0)				 
			--FROM 
			--	sHrm.tLeave L
			--	INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
			--	AND IsLWP = 1 AND StatusId=550
			--WHERE 
			--	L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
			--	AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
			--	AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
			--	AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
			--	AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
   -- 	        AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
	  -- 	    ) AS LWPNoOfLeave,
		 --  	ISNULL(LTM.IsLWP,0) AS IsLWP,
		 --  	(
			--	SELECT ISNULL(SUM(L.NoOfLeave),0)				 
			--	FROM 
			--		sHrm.tLeave L
			--		INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
			--		AND IsLWP = 0 AND StatusId=550
			--	WHERE 
			--		L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
			--		AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
			--		AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
			--		AND (MONTH(L.FromDate) < @rForMonth OR @rForMonth=0) 
			--		AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
   -- 				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		 --  	) AS UptoNoOfLeave,
		 --  	(
			--	SELECT ISNULL(SUM(L.NoOfLeave),0)				 
			--	FROM 
			--		sHrm.tLeave L
			--		INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
			--		AND IsLWP = 1 AND StatusId=550
			--	WHERE 
			--		L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
			--		AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
			--		AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
			--		AND (MONTH(L.FromDate) < @rForMonth OR @rForMonth=0) 
			--		AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
   -- 				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		 --  	) AS LWPUptoNoOfLeave,
		 --  	(
			--	SELECT ISNULL(SUM(L.NoOfLeave),0)				 
			--	FROM 
			--		sHrm.tLeave L
			--		INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
			--		AND IsLWP = 0 AND StatusId=550
			--	WHERE 
			--		L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
			--		AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
			--		AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
			--		AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
			--		AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
   -- 				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		 --  	) AS CurrentNoOfLeave,
		 --  	(
			--	SELECT ISNULL(SUM(L.NoOfLeave),0)				 
			--	FROM 
			--		sHrm.tLeave L
			--		INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
			--		AND IsLWP = 1 AND StatusId=550
			--	WHERE 
			--		L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
			--		AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
			--		AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
			--		AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0)
			--		AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
   -- 				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')='')) 
		 --  	) AS LWPCurrentNoOfLeave

		 ISNULL(LTM.IsLWP,0) AS IsLWP,
			ISNULL(NOL.NoOfLeave, 0) AS NoOfLeave,
			ISNULL(LWPNOL.NoOfLeave, 0) AS LWPNoOfLeave,
			ISNULL(UNOL.NoOfLeave, 0) AS UptoNoOfLeave,
			ISNULL(LWPUNOL.NoOfLeave, 0) AS LWPUptoNoOfLeave,
			ISNULL(CNOL.NoOfLeave, 0) AS CurrentNoOfLeave,
			ISNULL(LWPCNOL.NoOfLeave, 0) AS LWPCurrentNoOfLeave,
			--Mantis - 44992
			EM.EmployeeDesignation, 
			EM.DateOfJoining,
			EGM.Title AS EmployeeGroupName
			--Mantis - 44992
        FROM
			sHrm.vEmployeeCommonDetail EM
			--INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.OrgId = EM.OrgID AND LTGS.EmployeeGradeId =  EM.EmployeeGradeId
			--INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0 AND LTM.Id = LTGS.LeaveTypeId
			--inner JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EM.EmployeeId AND LTM.Id = LB.LeaveTypeId AND LB.BatchId=@rBatchId
			--inner JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.OrgId=EM.OrgID AND EM.EmployeeGradeId = EGM.Id
			----inner JOIN sHrm.tWorkingDays WD ON WD.EmployeeGradeId = EGM.Id AND WD.BatchId=@rBatchId AND WD.ForYear  = @rForYear
			----AND WD.ForMonth = @rForMonth

			LEFT JOIN sHrm.tLeaveTypeMaster LTM ON LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0 
			LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EM.EmployeeId AND LB.BatchId=@rBatchId AND LTM.Id = LB.LeaveTypeId
			LEFT JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id=EM.EmployeeGroupId
			LEFT JOIN (
				SELECT ISNULL(SUM(L.NoOfLeave),0) AS NoOfLeave, L.EmployeeId , L.LeaveTypeId	 
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')='')) AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
				GROUP BY L.EmployeeId, L.LeaveTypeId	
			) AS NOL ON EM.EmployeeId = NOL.EmployeeId AND LTM.Id = NOL.LeaveTypeId
			LEFT JOIN (
				SELECT ISNULL(SUM(L.NoOfLeave),0) AS NoOfLeave, L.EmployeeId , L.LeaveTypeId			 
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id AND IsLWP = 1 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')='')) AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
				GROUP BY L.EmployeeId, L.LeaveTypeId
	   		) AS LWPNOL ON EM.EmployeeId = LWPNOL.EmployeeId AND LTM.Id = LWPNOL.LeaveTypeId
			LEFT JOIN (
				SELECT ISNULL(SUM(L.NoOfLeave),0) AS NoOfLeave, L.EmployeeId , L.LeaveTypeId
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) AND (MONTH(L.FromDate) < @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')='')) AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
				GROUP BY L.EmployeeId, L.LeaveTypeId
		   	) AS UNOL ON EM.EmployeeId = UNOL.EmployeeId AND LTM.Id = UNOL.LeaveTypeId
		   	LEFT JOIN (
				SELECT ISNULL(SUM(L.NoOfLeave),0) AS NoOfLeave, L.EmployeeId , L.LeaveTypeId			 
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id AND IsLWP = 1 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) AND (MONTH(L.FromDate) < @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')='')) AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
				GROUP BY L.EmployeeId, L.LeaveTypeId
		   	) AS LWPUNOL ON EM.EmployeeId = LWPUNOL.EmployeeId AND LTM.Id = LWPUNOL.LeaveTypeId
		   	LEFT JOIN (
				SELECT ISNULL(SUM(L.NoOfLeave),0) AS NoOfLeave, L.EmployeeId , L.LeaveTypeId			 
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')='')) AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   		GROUP BY L.EmployeeId, L.LeaveTypeId
			) AS CNOL ON EM.EmployeeId = CNOL.EmployeeId AND LTM.Id = CNOL.LeaveTypeId
		   	LEFT JOIN (
				SELECT ISNULL(SUM(L.NoOfLeave),0) AS NoOfLeave, L.EmployeeId , L.LeaveTypeId							 
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id AND IsLWP = 1 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0)
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')='')) AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')='')) 
				GROUP BY L.EmployeeId, L.LeaveTypeId
		   	) AS LWPCNOL ON EM.EmployeeId = LWPCNOL.EmployeeId AND LTM.Id = LWPCNOL.LeaveTypeId
    	WHERE
    		EM.OrgID = @rOrgId 
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		--AND ((EM.EmployeeGroupId= @rEmployeeGroupId) OR (@rEmployeeGroupId= 0))
    		AND ((EM.DepartmentId= @rDepartmentId ) OR (@rDepartmentId= 0 ))
			AND (ISNULL(LTM.Id,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rLeaveTypeIds,',')) OR ISNULL(@rLeaveTypeIds, '')='')
    		ORDER BY EM.Code
END
GO
PRINT N'Altering Procedure [sIp].[pDeleteImportStockItem]...';


GO
ALTER   PROCEDURE [sIp].[pDeleteImportStockItem]
    @rOrgId int,
	@rXmldoc [nvarchar](max), 
	@rLocationId int
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
--DECLARE @lCount INT
--DECLARE @lInterrorCode INT,
--		@intDoc INT,
--        @1Code nvarchar(50),
--        @1StatusCode int  
       
       
--EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
--CREATE TABLE #tTable1 
-- (
--		Id bigint identity,
--        Code nvarchar(50)
           
--        --Id1 bigint NULL,
--        --departmentId int NULL
 
--  )
--  INSERT INTO #tTable1
--	(
--	    Code	   
--    ) 
--   SELECT
--        Code
--   FROM OPENXML (@intDoc, '/Table/ImportStockItem', 1)
--   With
--   ( 
--        Code nvarchar(50) '@Code'     
--   )     
   
--EXEC sp_xml_removedocument @intDoc
			
--SELECT @lCount =  COUNT(Id) FROM #tTable1
 
--WHILE @lCount > 0 
--  BEGIN

--       SELECT         
         
--         @1Code = Code       
         
--     FROM #tTable1 WHERE Id = @lCount    

--     IF EXISTS (SELECT 1 FROM sIp.tStockItemMaster WHERE Code = @1Code AND OrgId = @rOrgId AND LocationId=@rLocationId)         
--           BEGIN 
--  		        Delete From sIp.tStockItemMaster where Code = @1Code  		           		        
--  		        SET  @1StatusCode = 101   		        
--	       END
--	       Else
--	         BEGIN
--	            SET  @1StatusCode = -501 
--	         END
	       
--	  --ELSE IF NOT EXISTS(Select 1 From sHrm.tEmployeeMaster where Code = @lEmpNo)  
--	  --    BEGIN
--	  --             SET @1EmployeeNotFound = @1EmployeeNotFound + @lEmpNo + ' ,'  
	            
--	  --     END 
	         
--       SET @lCount = @lCount - 1		   	
	 
--   END		
		--Select @1StatusCode AS Result
		SELECT 0 AS Result
			 
END
GO
PRINT N'Altering Procedure [sOrderEntry].[pRptServiceItemComparativeStatement]...';


GO
ALTER   PROCEDURE [sOrderEntry].[pRptServiceItemComparativeStatement]
	@rFromDate [datetime] = '',
	@rId [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN	
	--Commented on 19/06/2025 - Invalid column name 'AccountingCurrencyId'.
	--DECLARE @lStartDate AS DATETIME
	--DECLARE @lEndDate AS DATETIME
	
	--DECLARE @tStatementTable TABLE (ItemTypeId SMALLINT, ItemTypeCode NVARCHAR(10), ItemTypeDescription NVARCHAR(100), ItemId SMALLINT, ItemCode NVARCHAR(50), ItemDescription NVARCHAR(300), CreatedDateTime NVARCHAR(12), Quantity INT, AverageUnitPrice Decimal(22,6), RevenueAmount Decimal(22,6))
	--DECLARE @tResultTableMonthOne TABLE (ItemTypeId SMALLINT, MainGroup NVARCHAR(100), ItemId SMALLINT, ItemName NVARCHAR(300), Qty INT, UP Decimal(22,6), Rev Decimal(22,6))
	--DECLARE @tResultTableMonthTwo TABLE (ItemTypeId SMALLINT, MainGroup NVARCHAR(100), ItemId SMALLINT, ItemName NVARCHAR(300), Qty INT, UP Decimal(22,6), Rev Decimal(22,6))
	--DECLARE @tResultTableMonthThree TABLE (ItemTypeId SMALLINT, MainGroup NVARCHAR(100), ItemId SMALLINT, ItemName NVARCHAR(300), Qty INT, UP Decimal(22,6), Rev Decimal(22,6))
	
	--SET @lStartDate = @rFromDate	
	----SET @lEndDate = DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, DATEADD(MM, 2, @rFromDate)) + 1, 0))
	--SET @lEndDate = DATEADD(MM, 3, @rFromDate)
	
	
	--INSERT INTO @tStatementTable
	--EXEC
	--('
	--SELECT	ItemTypeId,
	--		ItemTypeCode,
	--		ItemTypeDescription, 
	--		ItemId,
	--		ItemCode,
	--		ItemDescription, 
	--		CONVERT(NVARCHAR(3), DATENAME(M, CreatedDateTime)) + ''-'' + CONVERT(NVARCHAR(4), DATEPART(YY, CreatedDateTime)),
	--		SUM(Quantity) Quantity,
	--		(SUM(RevenueAmount) / SUM(Quantity)) AverageUnitPrice,
	--		SUM(RevenueAmount) RevenueAmount
	--FROM 

	--		(

	--		SELECT	DISTINCT(OE.Id) OrderEntryId,
	--				SITM.Id ItemTypeId,
	--				SITM.Code ItemTypeCode,
	--				SITM.Title ItemTypeDescription,
	--				SM.Id ItemId,
	--				SM.Code ItemCode,
	--				SM.Title ItemDescription, 
	--				BD.CreatedDateTime,
	--				OE.UnitPrice,
	--				OE.Quantity,
	--				(OE.CorporateAmount + OE.PatientAmount) AS RevenueAmount

	--		FROM	sOrderEntry.tOrderEntry OE

	--				INNER JOIN sOrderEntry.tBillingDetail BD
	--					ON BD.OrderEntryId = OE.Id
						
	--				INNER JOIN sOrderEntry.tServiceMaster SM
	--					ON SM.Id = OE.ItemSourceId
						
	--				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
	--					ON SITM.Id = SM.ServiceItemTypeId

	--		WHERE	OE.ItemSourceTypeId = 25
	--				AND OE.IsBilled = 1
	--				AND OE.IsObsolete = 0
	--				AND SITM.Id In ( ' + @rId + ')						
	--				AND BD.CreatedDateTime >= ''' + @lStartDate + '''
	--				AND BD.CreatedDateTime < ''' + @lEndDate + '''
	--		) RevenueDetails 

	--GROUP BY ItemTypeId, ItemTypeCode, ItemTypeDescription, ItemId, ItemCode, ItemDescription, (CONVERT(NVARCHAR(3), DATENAME(M, CreatedDateTime)) + ''-'' + CONVERT(NVARCHAR(4), DATEPART(YY, CreatedDateTime)))
	--ORDER BY ItemTypeDescription, ItemDescription')
	
	----SELECT  CreatedDateTime, ItemTypeId, ItemTypeCode, ItemTypeDescription, ItemId, ItemCode, ItemDescription, SUM(Quantity) AS Quantity, SUM(AverageUnitPrice) AS AverageUnitPrice, SUM(RevenueAmount) AS RevenueAmount FROM @tStatementTable
	----GROUP BY CreatedDateTime, AverageUnitPrice, RevenueAmount, ItemTypeDescription, ItemDescription, ItemTypeId, ItemTypeCode,  ItemId, ItemCode
	
	----SELECT  CreatedDateTime, ItemTypeId, ItemTypeCode, ItemTypeDescription, ItemId, ItemCode, ItemDescription, SUM(Quantity) AS Quantity, SUM(AverageUnitPrice) AS AverageUnitPrice, SUM(RevenueAmount) AS RevenueAmount FROM @tStatementTable	
	----WHERE CreatedDateTime = CONVERT(NVARCHAR(3), DATENAME(M, @lStartDate)) + '-' + CONVERT(NVARCHAR(4), DATEPART(YY, @lStartDate))
	----GROUP BY CreatedDateTime, AverageUnitPrice, RevenueAmount, ItemTypeDescription, ItemDescription, ItemTypeId, ItemTypeCode,  ItemId, ItemCode
	
	
	--INSERT INTO @tResultTableMonthOne	 
	--SELECT ItemTypeId, ItemTypeDescription, ItemId, ItemDescription, 
	--SUM(Quantity) AS Quantity, SUM(AverageUnitPrice) AS AverageUnitPrice, SUM(RevenueAmount) AS RevenueAmount 
	--FROM @tStatementTable WHERE CreatedDateTime = CONVERT(NVARCHAR(3), DATENAME(M, @lStartDate)) + '-' + CONVERT(NVARCHAR(4), DATEPART(YY, @lStartDate))
	--GROUP BY CreatedDateTime, AverageUnitPrice, RevenueAmount, ItemTypeDescription, ItemDescription, ItemTypeId, ItemTypeCode,  ItemId, ItemCode
	
	
	----SELECT ItemTypeId, MainGroup, ItemId, ItemName, Qty, UP, Rev FROM @tResultTableMonthOne	
	----GROUP BY ItemTypeId, MainGroup, ItemId, ItemName, Qty, UP, Rev
	
	--INSERT INTO @tResultTableMonthTwo
	--SELECT ItemTypeId, ItemTypeDescription, ItemId, ItemDescription, 
	--SUM(Quantity) AS Quantity, SUM(AverageUnitPrice) AS AverageUnitPrice, SUM(RevenueAmount) AS RevenueAmount 
	--FROM @tStatementTable WHERE CreatedDateTime = CONVERT(NVARCHAR(3), DATENAME(M, DATEADD(mm, 1, @lStartDate))) + '-' + CONVERT(NVARCHAR(4), DATEPART(YY, DATEADD(mm, 1, @lStartDate)))
	--GROUP BY CreatedDateTime, AverageUnitPrice, RevenueAmount, ItemTypeDescription, ItemDescription, ItemTypeId, ItemTypeCode,  ItemId, ItemCode
	
	----SELECT ItemTypeId, MainGroup, ItemId, ItemName, Qty, UP, Rev FROM @tResultTableMonthTwo	
	----GROUP BY ItemTypeId, MainGroup, ItemId, ItemName, Qty, UP, Rev		
	
	--INSERT INTO @tResultTableMonthThree
	--SELECT ItemTypeId, ItemTypeDescription, ItemId, ItemDescription, 
	--SUM(Quantity) AS Quantity, SUM(AverageUnitPrice) AS AverageUnitPrice, SUM(RevenueAmount) AS RevenueAmount 
	--FROM @tStatementTable WHERE CreatedDateTime = CONVERT(NVARCHAR(3), DATENAME(M, DATEADD(mm, 2, @lStartDate))) + '-' + CONVERT(NVARCHAR(4), DATEPART(YY, DATEADD(mm, 2, @lStartDate)))
	--GROUP BY CreatedDateTime, AverageUnitPrice, RevenueAmount, ItemTypeDescription, ItemDescription, ItemTypeId, ItemTypeCode,  ItemId, ItemCode
	
	----SELECT ItemTypeId, MainGroup, ItemId, ItemName, Qty, UP, Rev FROM @tResultTableMonthThree	
	----GROUP BY ItemTypeId, MainGroup, ItemId, ItemName, Qty, UP, Rev
	

	--SELECT  TS.ItemTypeDescription AS [Main Group], TS.ItemDescription AS [Item Name], 
	--ISNULL(T1.Qty, 0) AS [T1.Qty], ISNULL(T1.UP, 0) AS [T1.UP], ISNULL(T1.Rev, 0) AS [T1.Rev], 
	--ISNULL(T2.Qty, 0) AS [T2.Qty], ISNULL(T2.UP, 0) AS [T2.UP], ISNULL(T2.Rev, 0) AS [T2.Rev], 
	--ISNULL(T3.Qty, 0) AS [T3.Qty], ISNULL(T3.UP, 0) AS [T3.UP], ISNULL(T3.Rev, 0) AS [T3.Rev], 
	--CONVERT(NVARCHAR(3), DATENAME(M, @lStartDate)) + '-' + CONVERT(NVARCHAR(4), DATEPART(YY, @lStartDate)) AS [Month1], 
	--CONVERT(NVARCHAR(3), DATENAME(M, DATEADD(mm, 1, @lStartDate))) + '-' + CONVERT(NVARCHAR(4), DATEPART(YY, DATEADD(mm, 1, @lStartDate))) AS [Month2],
	--CONVERT(NVARCHAR(3), DATENAME(M, DATEADD(mm, 2, @lStartDate))) + '-' + CONVERT(NVARCHAR(4), DATEPART(YY, DATEADD(mm, 2, @lStartDate))) AS [Month3],
	--CONVERT(NVARCHAR(12), DATENAME(M, @lStartDate)) + '-' + CONVERT(NVARCHAR(4), DATEPART(YY, @lStartDate)) AS [FromMonthYear],
	--CONVERT(NVARCHAR(12), DATENAME(M, DATEADD(mm, 2, @lStartDate))) + '-' + CONVERT(NVARCHAR(4), DATEPART(YY, DATEADD(mm, 2, @lStartDate))) AS [ToMonthYear],
	--(SELECT '(' + CM.Code + ')'  AS Currency FROM sFinanceCommon.tCurrencyMaster CM
	--	INNER JOIN sCommon.tCompanyInformation CI ON CI.AccountingCurrencyId = CM.Id) AS CurrencyDisplay
	--FROM @tStatementTable TS
	--LEFT OUTER JOIN @tResultTableMonthOne T1 ON T1.ItemTypeId = TS.ItemTypeId AND 
	--		T1.ItemTypeId = TS.ItemTypeId AND 
	--		T1.ItemId = TS.ItemId
	--LEFT OUTER JOIN @tResultTableMonthTwo T2 ON T2.ItemTypeId = TS.ItemTypeId AND 			
	--		T2.ItemTypeId = TS.ItemTypeId AND 
	--		T2.ItemId = TS.ItemId
	--LEFT OUTER JOIN @tResultTableMonthThree T3 ON T3.ItemTypeId = TS.ItemTypeId AND			
	--		T3.ItemTypeId = TS.ItemTypeId AND 
	--		T3.ItemId = TS.ItemId
	--GROUP BY TS.ItemTypeDescription, TS.ItemDescription, TS.ItemTypeId, TS.ItemTypeCode,  TS.ItemId, TS.ItemCode,
	--T1.Qty, T1.UP, T1.Rev, T2.Qty, T2.UP, T2.Rev, T3.Qty, T3.UP, T3.Rev
	--ORDER BY TS.ItemTypeDescription, TS.ItemDescription

	SELECT  0 AS [Main Group], 
			0 AS [Item Name], 
			0 AS [T1.Qty], 0 AS [T1.UP], 0 AS [T1.Rev], 
			0 AS [T2.Qty], 0 AS [T2.UP], 0 AS [T2.Rev], 
			0 AS [T3.Qty], 0 AS [T3.UP], 0 AS [T3.Rev], 
			0 AS [Month1], 
			0 AS [Month2],
			0 AS [Month3],
			0 AS [FromMonthYear],
			0 AS [ToMonthYear],
			0 AS CurrencyDisplay
																	
END
GO
PRINT N'Altering Procedure [sProcurement].[pCurrencyRateForLppItemGet]...';


GO
ALTER   PROCEDURE [sProcurement].[pCurrencyRateForLppItemGet]
	@rOrgId [int],
	@rStockItemId [int] = 0
WITH EXECUTE AS CALLER
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
--    SELECT 
--    POD.Id AS Id, 
--	POD.ItemSourceId AS ItemId,
--	MAX(GRN.UpdatedDateTime) AS UpdatedDateTime 
--FROM 
--	sProcurement.tGoodsReceiptNoteDetail GRND
--	INNER JOIN sProcurement.tGoodsReceiptNote GRN ON GRND.GoodsReceiptNoteId = GRN.Id
--	INNER JOIN sProcurement.tPurchaseOrderDetail POD ON POD.Id = GRND.PurchaseOrderDetailId
--	INNER JOIN sProcurement.tPurchaseOrder PO ON PO.Id = POD.PurchaseOrderId
	 
--WHERE 
--	POD.ItemSourceId = @rStockItemId AND GRND.OrgId = @rOrgId 
--GROUP BY 
--	POD.ItemSourceId,  POD.Id
 SELECT 
    0 AS Id, 
	0 AS ItemId,
	0 AS UpdatedDateTime 

END
GO
PRINT N'Altering Procedure [sProcurement].[pPurchaseReOrderListGet]...';


GO
ALTER   PROCEDURE [sProcurement].[pPurchaseReOrderListGet]
	@rOrgId [int] = 0,
	@rReorderListXml [nvarchar](max) = '' 
	 
WITH EXECUTE AS CALLER
AS
BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--SET NOCOUNT ON
	--	DECLARE @loIdoc INT
	--	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rReorderListXml
		
		 
	--	SELECT	SIM.Id,
	--			SIM.Code, 
	--			SIM.Title, 				 
	--			ISNULL(POD4.NetUnitPrice, 0),  					  
	--			ISNULL(TaxGroupId, 0)TaxGroupId,
	--			ISNULL(TGM.Code, '') TaxCode,
	--			ISNULL(TGM.Title, '') TaxTitle,
	--			sTax.fExtTaxRateGet(TaxGroupId, sCommon.fGetDate()) TaxRate,
	--			ISNULL(POD4.PurchaseUomId, 1) PurchaseUomId,
	--			ISNULL(SU.Code, '') UomCode,
	--			ISNULL(SU.Title, '') UomTile,			 
	--			sCommon.fGetDate() RequestedDeliveryDate,
	--			34 AS ItemSourceTypeId,
	--			SIM.IsBatchWiseTracking
				
				
	--	FROM 
	--			sIP.vExtStockItemMaster SIM
	--	LEFT JOIN 
	--			(SELECT POD3.Id, POD3.StockItemId, POD3.PurchaseUomId, POD3.NetUnitPrice, SIPU.StockUomId FROM
	--				(SELECT POD1.Id, POD1.StockItemId, POD2.StockItemPurchaseUomId PurchaseUomId, POD2.NetUnitPrice   FROM 
	--				(SELECT Max(POD.Id) Id, POD.ItemSourceId AS StockItemId  FROM sProcurement.tPurchaseOrderDetail POD
	--				WHERE POD.OrgId = @rOrgId
	--					GROUP BY POD.ItemSourceId
	--				  HAVING POD.ItemSourceId IN (SELECT  Id	FROM OPENXML (@loIdoc, '/PurchaseOrder/ReorderList', 1)
	--												WITH	( 
	--															Id INT
	--														) 
	--											)) POD1
	--				INNER JOIN
	--						sProcurement.tPurchaseOrderDetail POD2
	--				ON
	--						POD2.Id = POD1.Id
	--				INNER JOIN sProcurement.tPurchaseOrder PO
	--				ON
	--						PO.Id = POD2.PurchaseOrderId AND PO.StatusId = 43 AND PO.OrgId = @rOrgId)  POD3
	--			INNER JOIN 
	--					sIp.tStockItemPurchaseUom SIPU
	--			ON 
	--					SIPU.Id = POD3.PurchaseUomId
	--			)POD4
	--	ON
	--			POD4.StockItemId = SIM.Id
	--	LEFT JOIN 
	--			sFinanceCommon.tStockUomMaster SU
	--	ON
	--			SU.Id = POD4.StockUomId
	--	LEFT JOIN 
	--			sTax.vExtTaxGroupMaster TGM
	--	ON
	--			TGM.Id = SIM.TaxGroupId	
 
	--	WHERE SIM.Id IN (SELECT  Id	FROM OPENXML (@loIdoc, '/PurchaseOrder/ReorderList', 1)
	--						WITH	( 
	--									Id INT
	--								) 
		
	--					)
	--					AND SIM.OrgId = @rOrgId
	SELECT 0 AS Result
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockAuditRetrieve]...';


GO
ALTER   PROCEDURE [sProcurement].[pRptStockAuditRetrieve]
	@rOrgId [int],
	@rLocationId [int] = 0,
	@rItemMainGroupId [int] = 0,
	@rItemSubGroupId [int] = 0,
	@rStockItemId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--SELECT 
	--	SB.StockItemId,
	--	SIM.Code AS ItemCode,
	--	SIM.Title AS ItemName,
	--	BIM.Title AS BinRef,
	--	SUM(SB.AvailableQuantity) AS SQuantity,
	--	SLM.Title AS StoreLocation
										 
	--FROM sIp.tStockItemMaster SIM
	--	INNER JOIN sProcurement.tStockBatch SB
	--	ON 
	--		SIM.Id = SB.StockItemId	   
	--	INNER JOIN sIp.tItemSubGroupMaster ISG
	--	ON
	--		ISG.Id = SIM.ItemSubGroupId
	--	INNER JOIN sIp.tStoreLocationMaster SLM
	--	ON
	--		SLM.Id = SB.StoreLocationId
	--	INNER JOIN sIp.tStockItemBin SIB
	--	ON
	--		SIB.StockItemId = SIM.Id
	--	INNER JOIN sIp.tBinMaster BIM
	--	ON 
	--		BIM.Id = SIB.BinId
	--  WHERE SIM.OrgId = @rOrgId
	--	GROUP BY SB.StockItemId, SB.StoreLocationId, SIM.ItemSubGroupId, ISG.ItemMainGroupId, SIM.Code, SIM.Title, SLM.Title, BIM.Title
	--	HAVING ((SB.StockItemId = @rStockItemId) OR (@rStockItemId = 0))
	  
	--	AND ((SB.StoreLocationId = @rLocationId) OR (@rLocationId = 0))
	--	AND ((SIM.ItemSubGroupId = @rItemSubGroupId) OR (@rItemSubGroupId = 0))
	--	AND ((ISG.ItemMainGroupId = @rItemMainGroupId) OR (@rItemMainGroupId = 0))
	  
	  SELECT 
		0 AS StockItemId,
		0 AS ItemCode,
		0 AS ItemName,
		0 AS BinRef,
		0 AS SQuantity,
		0 AS StoreLocation
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockIssueReturnRegisterGet]...';


GO

ALTER PROCEDURE [sProcurement].[pRptStockIssueReturnRegisterGet]
  @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100),
	@rOrgGroupId int,
	@rFromDate Date = '',
	@rToDate Date = '',
	@rDetail bit =0,
	@rFromReturnNo int = 0,		-- #Start Mantis Id : 0035096
	@rToReturnNo int = 0,			
	@rFromReturnNoYear int = 0,
	@rToReturnNoYear int = 0,
	@rFromReturnDate Date = null,
	@rToReturnDate	Date = null	-- #End Mantis Id : 0035096
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
				SIM.Code AS ItemCode,
				SIM.Title AS ItemName,		
				SI.ReturnedByName,	
				SI.Number AS Billno, 	
				SI.CreatedDateTime AS IssuedDate,
				SIND.IssuedQuantity, 
				SB.ExpiryDate,
				SB.ItemRate AS Amount,
				--SB.Number As BatchNumber,
				SI.Id, 
				@rDetail AS Detail,
				@rBuilder1 As Builder1,
				@rBuilder2 AS Builder2,
				SIRB.ReturnQuantity,
				PSI.Remark,--mantis - 0032620
				SIP.WeightedAverageCost			-- MantisId : 0034833
				--start : mantis : 0044576
				,PSI.IssueToSourceId
				,ISNULL(PSI.IssueToSourceTypeId,0) AS IssueToSourceTypeId
				,A.Id AS AcademicId
				,SM.Code AS StudentCode
				,SM.FirstName AS StudentFirstName
				,SM.LastName AS StudentLastName
				,SM.MiddleName AS StudentMiddleName
				,CM.DisplayTitle AS ClassName
				,DM.DisplayTitle AS DivisionName
				,CM.OrderIndex AS ClassOrderIndex
				,DM.OrderIndex AS DivisionOrderIndex
				,EM.Code AS EmployeeCode
				,EM.FirstName AS EmployeeFirstName
				,EM.LastName AS EmployeeLastname
				,EM.MiddleName AS EmployeeMiddleName
				,ODM.Title AS EmployeeDepartmentName
				--end : mantis : 0044576
		FROM  sProcurement.tStockIssueReturn SI
		INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SI.Id
		INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id=SIRB.StockIssueBatchId
		INNER JOIN sProcurement.tStockIssueDetail SIND ON SIND.Id=SIB.StockIssueDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON SIND.StockItemId  = SIM.Id 
		LEFT JOIN sProcurement.tStockBatch SB ON SB.Id = SIB.StockBatchId
	     
	    INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
		INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
		LEFT JOIN sIp.tStockItemCategoryMaster SICM ON SICM.Id=SIM.StockItemCategoryId	
		LEFT Join sProcurement.tStockIssue PSI on PSI.ID = SI.StockIssueId--mantis - 0032620
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId		-- MantisId : 0034833
		--start : mantis : 0044576
		LEFT JOIN sStudent.tAcademic A ON A.Id = PSI.IssueToSourceId 
		AND PSI.IssueToSourceTypeId = 2001
		LEFT JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId 
		LEFT JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id =PSI.IssueToSourceId AND  PSI.IssueToSourceTypeId = 95
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId 
		LEFT JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id
		--end : mantis : 0044576
		  WHERE	     
	     SIM.IsObsolete=0
		--AND(SB.StoreLocationId= @rStoreLocationId)
		AND (IMGM.Id = @rMainGroupId OR @rMainGroupId=0)
		
		AND (ISGM.Id = @rSubGroupId OR @rSubGroupId=0)
		AND (SICM.Id = @rStockItemCategoryId OR @rStockItemCategoryId = 0)
		AND (SIM.Code = @rItemCode OR @rItemCode = '')
		AND (SIM.Title = @rItemName OR @rItemName = '')
		AND ((CAST(SI.CreatedDateTime AS Date) >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) 
		AND ((CAST(SI.CreatedDateTime AS Date) <= @rToDate) OR (ISNULL(@rToDate,'') = '') )
		AND SI.OrgGroupId=@rOrgGroupId
		AND SB.StoreLocationId =@rStoreLocationId
		----AND (SB.OrgId = @rOrgId)
		-- #Start Mantis Id : 0035096
		AND ((SI.Number IS NOT NULL AND LEN(SI.Number) >= 7 AND ISNUMERIC(SUBSTRING(SI.Number, 4, 2)) = 1 AND ISNUMERIC(SUBSTRING(SI.Number, 7, LEN(SI.Number) - 6)) = 1 
			AND (CAST(SUBSTRING(SI.Number, 4, 2) AS INT) > @rFromReturnNoYear OR (CAST(SUBSTRING(SI.Number, 4, 2) AS INT) = @rFromReturnNoYear AND CAST(SUBSTRING(SI.Number, 7, LEN(SI.Number) - 6) AS INT) >= @rFromReturnNo)))
			OR @rFromReturnNoYear = 0 OR @rFromReturnNo = 0)
		AND ((SI.Number IS NOT NULL AND LEN(SI.Number) >= 7 AND ISNUMERIC(SUBSTRING(SI.Number, 4, 2)) = 1 AND ISNUMERIC(SUBSTRING(SI.Number, 7, LEN(SI.Number) - 6)) = 1 
			AND (CAST(SUBSTRING(SI.Number, 4, 2) AS INT) < @rToReturnNoYear OR (CAST(SUBSTRING(SI.Number, 4, 2) AS INT) = @rToReturnNoYear AND CAST(SUBSTRING(SI.Number, 7, LEN(SI.Number) - 6) AS INT) <= @rToReturnNo)))
			OR @rToReturnNoYear = 0 OR @rToReturnNo = 0)
		AND (SI.TransactionDate >= @rFromReturnDate OR @rFromReturnDate IS NULL)
		AND (SI.TransactionDate <= @rToReturnDate OR @rToReturnDate IS NULL)
		-- #End Mantis Id : 0035096
		 
    Order  by SIM.Title	
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockMovement]...';


GO
ALTER   PROCEDURE [sProcurement].[pRptStockMovement]
	@rOrgId int,
	@rLocationId [int] = 0,
	@rId [int] = 0,
	@rItemMainGroupId [int] = 0,
	@rFromDate [datetime] = '1900/1/1',
	@rToDate [datetime] = '1900/1/1'
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
--Commented on 19/06/2025 - Invalid column name 'OrgId'. 

--DECLARE @lMainGroupCode VARCHAR(20)
--DECLARE @lMainGroupTitle VARCHAR(20)
--DECLARE @lSubGroupCode VARCHAR(20)
--DECLARE @lSubGroupTitle VARCHAR(20)
--DECLARE @lStockItemCode VARCHAR(20)
--DECLARE @lStockItemTitle VARCHAR(20)
--DECLARE @lLocation VARCHAR(20)
 
--IF (@rId <> 0)
--	BEGIN
--		SELECT @lMainGroupCode = SIM.MainGroupCode FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId AND OrgId = @rOrgId
--		SELECT @lMainGroupTitle = SIM.MainGroupTitle FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId AND OrgId = @rOrgId
--		SELECT @lSubGroupCode = SIM.SubGroupCode FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId AND OrgId = @rOrgId
--		SELECT @lSubGroupTitle = SIM.SubGroupTitle FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId AND OrgId = @rOrgId
--		SELECT @lStockItemCode = SIM.StockItemCode FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId AND OrgId = @rOrgId
--		SELECT @lStockItemTitle = SIM.StockItemTitle FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId AND OrgId = @rOrgId
--	END

--ELSE IF (@rItemMainGroupId <> 0)
--	BEGIN
--		SELECT @lMainGroupCode = SIM.MainGroupCode FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.MainGroupId = @rItemMainGroupId	AND OrgId = @rOrgId
--		SELECT @lMainGroupTitle = SIM.MainGroupTitle FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.MainGroupId = @rItemMainGroupId	AND OrgId = @rOrgId
--		SELECT @lSubGroupCode = SIM.SubGroupCode FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.MainGroupId = @rItemMainGroupId	AND OrgId = @rOrgId
--		SELECT @lSubGroupTitle = SIM.SubGroupTitle FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.MainGroupId = @rItemMainGroupId	AND OrgId = @rOrgId
--		SELECT @lStockItemCode = SIM.StockItemCode FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.MainGroupId = @rItemMainGroupId AND OrgId = @rOrgId
--		SELECT @lStockItemTitle = SIM.StockItemTitle FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.MainGroupId = @rItemMainGroupId AND OrgId = @rOrgId
--	END        

--SELECT @lLocation = SLM.Title FROM sIp.tStoreLocationMaster SLM WHERE SLM.Id = @rLocationId AND OrgId = @rOrgId

--BEGIN
 
-- SELECT RefNo,
--Module,
--Location,
--StockItemCodeName,
--ItemCodeName,
--FromDate, 
--ToDate, 
--MovementDate,
--WACId, 
--ExpiryDate,
--Uom,
--ROUND(Wac, 2) Wac,
--FromLocation,
--ToLocation,
--QtyOut,
--QtyIn, 
--QtyBalance,
--ROUND(AmountBalance, 2) AmountBalance, 
--MainGroupCode,
--MainGroupTitle,
--SubGroupCode, 
--SubGroupTitle,
--StockItemCode,
--StockItemTitle
-- FROM
--      (SELECT     GRN.RefNumber                                                               AS RefNo, 
--				'GRN'																				 AS Module,  
--				(CASE 
--					WHEN @rLocationId <> 0 THEN
--						@lLocation
--					ELSE
--						'ALL'
--					END
--				)																AS Location,
				
--				(CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemCode + '-' + @lStockItemTitle
--					ELSE
--						'ALL'															 
--					END
--				)  AS StockItemCodeName, 
--                (CASE
--					WHEN(@rItemMainGroupId <> 0) THEN
--                        @lMainGroupCode + '-' + @lMainGroupTitle
--                    ELSE
--						'ALL'
--					END
--				)    											 AS ItemCodeName, 
--                  (CASE @rFromDate
--                              WHEN '1900/1/1' THEN
--                                    '1900/1/1'
--                              ELSE
--                                    @rFromDate  
--                              END
--                  )                                                                                               AS FromDate, 
--                  (CASE @rToDate
--                              WHEN '1900/1/1' THEN
--                                    sCommon.fGetDate()
--                              ELSE
--                                    @rToDate    
--                              END
--                  )                                                                                               AS ToDate, 
                  
--                  WAC.CreatedDateTime																			 AS MovementDate, 
--                  WAC.Id																					     AS WACId,		
--                  GRN.ExpiryDate																				AS ExpiryDate, 
--                  SIP.Uom                                                                                              AS Uom, 
                  
--                  WAC.WeightedAverageCost																		 AS Wac, 
--                  ''                                                                                 AS FromLocation, 
--                  (CASE 
--                        WHEN WAC.SourceTypeId = 46 AND WAC.IsReceipt = 1 THEN
--                              SLM.Title
--                        ELSE
--                              ''
--                        END
--                    )   																	  AS ToLocation, 
--                  (CASE 
--                        WHEN WAC.IsReceipt = 0 THEN 
--                              WAC.Quantity END
--                  )                                                                                               AS QtyOut, 
                  
--                  (CASE 
--                        WHEN WAC.IsReceipt = 1 THEN 
--                              WAC.Quantity END
--                  )                                                                                               AS QtyIn, 
                  
--                  (CASE 
--					WHEN @rLocationId <> 0 THEN
--						WAC.StoreLocationClosingQuantity
--					ELSE
--						WAC.ClosingQuantity
--					END
--				  )		AS QtyBalance, 
--                  (CASE 
--					WHEN @rLocationId <> 0 THEN
--						(ROUND(WAC.WeightedAverageCost, 2) * WAC.StoreLocationClosingQuantity)
--					ELSE
--						(ROUND(WAC.WeightedAverageCost, 2) * WAC.ClosingQuantity)
--					END
--				  )		AS AmountBalance, 
                  
--                  (CASE 
--					WHEN (@rId <> 0 OR @rItemMainGroupId <> 0) THEN
--						@lMainGroupCode
--					ELSE
--						SIM.MainGroupCode															 
--					END
--				  )																								AS MainGroupCode, 
--				  (CASE 
--					WHEN (@rId <> 0 OR @rItemMainGroupId <> 0) THEN
--						@lMainGroupTitle
--					ELSE
--						SIM.MainGroupTitle															 
--					END
--				  )																								AS MainGroupTitle, 
--				  (CASE 
--					WHEN (@rId <> 0 OR @rItemMainGroupId <> 0) THEN
--						@lSubGroupCode
--					ELSE
--						SIM.SubGroupCode															 
--					END
--				  )																								AS SubGroupCode, 
--				  (CASE 
--					WHEN (@rId <> 0 OR @rItemMainGroupId <> 0) THEN
--						@lSubGroupTitle
--					ELSE
--						SIM.SubGroupTitle															 
--					END
--				  )																								AS SubGroupTitle, 
--				  (CASE 
--					WHEN (@rId <> 0 OR @rItemMainGroupId <> 0) THEN
--						@lStockItemCode
--					ELSE
--						SIM.StockItemCode															 
--					END
--				  )																								AS StockItemCode, 
--				  (CASE 
--					WHEN (@rId <> 0 OR @rItemMainGroupId <> 0) THEN
--						@lStockItemTitle
--					ELSE
--						SIM.StockItemTitle															 
--					END
--				  )																						AS StockItemTitle,
--				  0 AS openingbalance
	                   
--      FROM  sIp.tWeightedAverageCostLog AS WAC
--                  INNER JOIN sIp.tStoreLocationMaster SLM
--                        ON WAC.StoreLocationId = SLM.Id 
--                  INNER JOIN (SELECT		GRN.Number RefNumber,  
--										GRNB.ExpiryDate ExpiryDate, 
--                                        GRN.DeliveryOrderDate Date, 
--                                        GRNB.Id
--                              FROM sProcurement.vExtGoodsReceiptNoteBatch GRNB
--									   INNER JOIN sProcurement.vExtGoodsReceiptNoteDetail GRND
--                                            ON GRND.Id = GRNB.GoodsReceiptNoteDetailId
--                                       INNER JOIN sProcurement.vExtGoodsReceiptNote GRN
--                                            ON GRN.Id = GRND.GoodsReceiptNoteId AND GRNB.OrgId = @rOrgId) GRN    
                               
--						 ON GRN.Id = WAC.SourceId AND WAC.SourceTypeId = 46
--                  INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
--                  INNER JOIN (SELECT SIP.Id, SIP.IssueStockUomId, SUom.Title Uom
--								FROM sIp.vExtStockItemMaster SIP
--									INNER JOIN sFinanceCommon.tStockUomMaster SUom
--										ON SIP.IssueStockUomId = SUom.Id WHERE SIP.OrgId = @rOrgId)SIP
--						ON SIM.StockItemId = SIP.Id 
					
                                    
--WHERE ((WAC.CreatedDateTime >= @rFromDate AND WAC.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
--  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId, 0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId, 0) = 0))
--  AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId, 0) = 0))
--  AND WAC.OrgId = @rOrgId
                  
--UNION

--       SELECT     GRNR.RefNumber                                                               AS RefNo,
--				'GRNR'																				 AS Module,
--				(CASE 
--					WHEN @rLocationId <> 0 THEN
--						@lLocation
--					ELSE
--						'ALL'
--					END
--				)																AS Location, 
				
--				(CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemCode + '-' + @lStockItemTitle
--					ELSE
--						SIM.StockItemCode + '-' + SIM.StockItemTitle															 
--					END
--				)  AS StockItemCodeName, 
--                (CASE
--					WHEN(@rItemMainGroupId <> 0) THEN
--                        @lMainGroupCode + '-' + @lMainGroupTitle
--                    ELSE
--						'ALL'
--					END
--				)    											 AS ItemCodeName, 
--                  (CASE @rFromDate
--                              WHEN '1900/1/1' THEN
--                                    '1900/1/1'
--                              ELSE
--                                    @rFromDate  
--                              END
--                  )                                                                                               AS FromDate,
--                  (CASE @rToDate
--                              WHEN '1900/1/1' THEN
--                                    sCommon.fGetDate()
--                              ELSE
--                                    @rToDate    
--                              END
--                  )                                                                                               AS ToDate,
                  
--                  WAC.CreatedDateTime                                                                       AS MovementDate,
--                  WAC.Id																					     AS WACId,		
--                  GRNR.ExpiryDate                                                                   AS ExpiryDate,
--                  SIP.Uom                                                                                              AS Uom,
                  
--                  WAC.WeightedAverageCost                                                             AS Wac,
--                 (CASE 
--                        WHEN WAC.SourceTypeId = 47 AND WAC.IsReceipt = 0 THEN
--                              SLM.Title
--                        ELSE
--                              ''
--                        END)                                                                                 AS FromLocation,
--                   ''                                                                            AS ToLocation,
--                  (CASE 
--                        WHEN WAC.IsReceipt = 0 THEN 
--                              WAC.Quantity END
--                  )                                                                                               AS QtyOut,
                  
--                  (CASE 
--                        WHEN WAC.IsReceipt = 1 THEN 
--                              WAC.Quantity END
--                  )                                                                                               AS QtyIn,
                  
--                  (CASE 
--					WHEN @rLocationId <> 0 THEN
--						WAC.StoreLocationClosingQuantity
--					ELSE
--						WAC.ClosingQuantity
--					END
--				  )		AS QtyBalance, 
--                  (CASE 
--					WHEN @rLocationId <> 0 THEN
--						(ROUND(WAC.WeightedAverageCost, 2) * WAC.StoreLocationClosingQuantity)
--					ELSE
--						(ROUND(WAC.WeightedAverageCost, 2) * WAC.ClosingQuantity)
--					END
--				  )		AS AmountBalance, 
                  
--                 (CASE 
--					WHEN (@rId <> 0) THEN
--						@lMainGroupCode
--					ELSE
--						SIM.MainGroupCode															 
--					END
--				  )																								AS MainGroupCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lMainGroupTitle
--					ELSE
--						SIM.MainGroupTitle															 
--					END
--				  )																								AS MainGroupTitle, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lSubGroupCode
--					ELSE
--						SIM.SubGroupCode															 
--					END
--				  )																								AS SubGroupCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lSubGroupTitle
--					ELSE
--						SIM.SubGroupTitle															 
--					END
--				  )																								AS SubGroupTitle, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemCode
--					ELSE
--						SIM.StockItemCode															 
--					END
--				  )																								AS StockItemCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemTitle
--					ELSE
--						SIM.StockItemTitle															 
--					END
--				  )		   AS StockItemTitle,
--				    0 AS openingbalance
				    
--	--			 (
				  
--	--			 SELECT    TOP 1 
--	--			  (CASE 
-- --                       WHEN   @lLocation <> 0 THEN 
-- --                       WA.StoreLocationClosingQuantity                              
-- --                       WHEN   @lLocation = 0 THEN
--	--						  WA.ClosingQuantity						 
-- --                       END
-- --                 )      							AS OpeningBalance	
-- --FROM  sIp.tWeightedAverageCostLog WA
-- --WHERE ((WA.SourceId  = WAC.SourceId) AND WA.SourceTypeId = 47
-- --AND ((WA.CreatedDateTime >= @rFromDate AND WA.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate())))
-- --ORDER BY WA.CreatedDateTime DESC )																						AS OpeningBalance
                  
                  
--      FROM  sIp.tWeightedAverageCostLog AS WAC
--                  INNER JOIN sIp.tStoreLocationMaster SLM
--                        ON WAC.StoreLocationId = SLM.Id 
--                  INNER JOIN (SELECT		GRNR.Number RefNumber,
--										GRNB.ExpiryDate ExpiryDate,
--                                        GRNR.DeliveryOrderDate Date,
--                                        GRNRB.Id
--                              FROM sProcurement.vExtGoodsReceiptNoteReturnBatch GRNRB
--									   INNER JOIN sProcurement.vExtGoodsReceiptNoteReturnDetail GRNRD
--                                            ON GRNRD.Id = GRNRB.GoodsReceiptNoteReturnDetailId
--                                       INNER JOIN sProcurement.vExtGoodsReceiptNoteReturn GRNR
--                                            ON GRNR.Id = GRNRD.GoodsReceiptNoteReturnId
--                                       INNER JOIN sProcurement.vExtGoodsReceiptNoteBatch GRNB
--                                            ON GRNRB.GoodsReceiptNoteBatchId = GRNB.Id
--                                            AND GRNRB.OrgId = @rOrgId ) GRNR    
                               
--						 ON GRNR.Id = WAC.SourceId AND WAC.SourceTypeId = 47
--                  INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
--                  INNER JOIN (SELECT SIP.Id, SIP.IssueStockUomId, SUom.Title Uom
--								FROM sIp.vExtStockItemMaster SIP
--									INNER JOIN sFinanceCommon.tStockUomMaster SUom
--										ON SIP.IssueStockUomId = SUom.Id AND SIP.OrgId =  @rOrgId)SIP
--						ON SIM.StockItemId = SIP.Id
                                    
--WHERE ((WAC.CreatedDateTime >= @rFromDate AND WAC.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
--  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId, 0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId, 0) = 0))
--  AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId, 0) = 0))
--   AND WAC.OrgId = @rOrgId
                  
 
----UNION
 
 
----      SELECT     D.RefNumber                                                               AS RefNo,
----				'PharmacyDispense'																				 AS Module,
----				(CASE 
----					WHEN @rLocationId <> 0 THEN
----						@lLocation
----					ELSE
----						'ALL'
----					END
----				)																AS Location, 
				
----				(CASE 
----					WHEN (@rId <> 0) THEN
----						@lStockItemCode + '-' + @lStockItemTitle
----					ELSE
----						SIM.StockItemCode + '-' + SIM.StockItemTitle															 
----					END
----				)  AS StockItemCodeName, 
----               (CASE
----					WHEN(@rItemMainGroupId <> 0) THEN
----                        @lMainGroupCode + '-' + @lMainGroupTitle
----                    ELSE
----						'ALL'
----					END
----				)    											 AS ItemCodeName, 
----                  (CASE @rFromDate
----                              WHEN '1900/1/1' THEN
----                                    '1900/1/1'
----                              ELSE
----                                    @rFromDate  
----                              END
----                  )                                                                                               AS FromDate,
----                  (CASE @rToDate
----                              WHEN '1900/1/1' THEN
----                                    sCommon.fGetDate()
----                              ELSE
----                                    @rToDate    
----                              END
----                  )                                                                                               AS ToDate,
                  
----                  WAC.CreatedDateTime                                                                       AS MovementDate,
----                  WAC.Id																					     AS WACId,		
----                  D.ExpiryDate                                                                   AS ExpiryDate,
----                  SIP.Uom                                                                                              AS Uom,
                  
----                  WAC.WeightedAverageCost                                                             AS Wac,
----                  (CASE 
----                        WHEN WAC.SourceTypeId = 65 AND WAC.IsReceipt = 0 THEN
----                              SLM.Title
----                        ELSE
----                              ''
----                        END
----                    )                                                                                 AS FromLocation,
----                    ''                                                                             AS ToLocation,
----                  (CASE 
----                        WHEN WAC.IsReceipt = 0 THEN 
----                              WAC.Quantity END
----                  )                                                                                               AS QtyOut,
                  
----                  (CASE 
----                        WHEN WAC.IsReceipt = 1 THEN 
----                              WAC.Quantity END
----                  )                                                                                               AS QtyIn,
                  
----                  (CASE 
----					WHEN @rLocationId <> 0 THEN
----						WAC.StoreLocationClosingQuantity
----					ELSE
----						WAC.ClosingQuantity
----					END
----				  )		AS QtyBalance, 
----                  (CASE 
----					WHEN @rLocationId <> 0 THEN
----						(ROUND(WAC.WeightedAverageCost, 2) * WAC.StoreLocationClosingQuantity)
----					ELSE
----						(ROUND(WAC.WeightedAverageCost, 2) * WAC.ClosingQuantity)
----					END
----				  )		AS AmountBalance, 
                  
----                 (CASE 
----					WHEN (@rId <> 0) THEN
----						@lMainGroupCode
----					ELSE
----						SIM.MainGroupCode															 
----					END
----				  )																								AS MainGroupCode, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lMainGroupTitle
----					ELSE
----						SIM.MainGroupTitle															 
----					END
----				  )																								AS MainGroupTitle, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lSubGroupCode
----					ELSE
----						SIM.SubGroupCode															 
----					END
----				  )																								AS SubGroupCode, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lSubGroupTitle
----					ELSE
----						SIM.SubGroupTitle															 
----					END
----				  )																								AS SubGroupTitle, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lStockItemCode
----					ELSE
----						SIM.StockItemCode															 
----					END
----				  )																								AS StockItemCode, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lStockItemTitle
----					ELSE
----						SIM.StockItemTitle															 
----					END
----				  )		   AS StockItemTitle,
----				    0 AS openingbalance
                  
----      FROM  sIp.tWeightedAverageCostLog AS WAC
----                  INNER JOIN sIp.tStoreLocationMaster SLM
----                        ON WAC.StoreLocationId = SLM.Id  
----       --           INNER JOIN (SELECT		'' RefNumber,
----							--			SB.ExpiryDate ExpiryDate,
----       --                                 D.createdDateTime Date,
----       --                                 DB.Id
----       --                       FROM sPharmacy.vExtDispenseBatch DB
----							--		   INNER JOIN sPharmacy.vExtDispense D
----       --                                     ON D.Id = DB.DispenseId
----       --                                INNER JOIN sProcurement.vExtStockBatch SB
----							--				ON DB.BatchSourceId = SB.Id) D
----						 --ON D.Id = WAC.SourceId AND WAC.SourceTypeId = 65
----                         INNER JOIN (SELECT		BD.BillNumber  RefNumber,
----										SB.ExpiryDate ExpiryDate,
----                                        OE.CreatedDateTime Date,
----                                        OEB.Id
----                              FROM sOrderEntry.vExtOrderEntryBatch OEB
----                                       INNER JOIN sOrderEntry.vExtOrderEntry OE
----                                            ON OE.Id = OEB.OrderEntryId AND OE.OrderSourceScreenId = 5
----                                        INNER JOIN sOrderEntry.vExtBillingDetail BD
----											ON OE.Id = BD.OrderEntryId 										                                            
----          --                             INNER JOIN sOrderEntry.vExtBillingDetail BD
----										--	ON BD.OrderEntryId = OE.Id
----										--INNER JOIN sOrderEntry.vExtBilling B
----										--	ON B.Id = BD.BillingId
----                                       INNER JOIN sProcurement.tStockBatch SB
----                                             ON OEB.BatchSourceId = SB.Id AND OEB.OrgId = @rOrgId) D 
----                        ON D.Id = WAC.SourceId AND WAC.SourceTypeId = 65
----                  INNER JOIN  sIp.vExtStockItemMainGroupList SIM
----                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34       
----                  INNER JOIN (SELECT SIP.Id, SIP.IssueStockUomId, SUom.Title Uom
----								FROM sIp.vExtStockItemMaster SIP
----									INNER JOIN sFinanceCommon.tStockUomMaster SUom
----										ON SIP.IssueStockUomId = SUom.Id AND SIP.OrgId =  @rOrgId)SIP
----						ON SIM.StockItemId = SIP.Id                  
----WHERE ((WAC.CreatedDateTime >= @rFromDate AND WAC.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
----  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId, 0) = 0))
----  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId, 0) = 0))
----  AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId, 0) = 0))
----  AND WAC.OrgId = @rOrgId          
    
---- UNION
 
----      SELECT     POS.RefNumber                                                                   AS RefNo, 
----				 'POS'																				 AS Module,
----				(CASE 
----					WHEN @rLocationId <> 0 THEN
----						@lLocation
----					ELSE
----						'ALL'
----					END
----				)																AS Location,
				
----				(CASE 
----					WHEN (@rId <> 0) THEN
----						@lStockItemCode + '-' + @lStockItemTitle
----					ELSE
----						SIM.StockItemCode + '-' + SIM.StockItemTitle															 
----					END
----				)  AS StockItemCodeName, 
----                (CASE
----					WHEN(@rItemMainGroupId <> 0) THEN
----                        @lMainGroupCode + '-' + @lMainGroupTitle
----                    ELSE
----						'ALL'
----					END
----				)    											 AS ItemCodeName, 
----                  (CASE @rFromDate
----                              WHEN '1900/1/1' THEN
----                                    '1900/1/1'
----                              ELSE
----                                    @rFromDate  
----                              END
----                  )                                                                                               AS FromDate,
----                  (CASE @rToDate
----                              WHEN '1900/1/1' THEN
----                                    sCommon.fGetDate()
----                              ELSE
----                                    @rToDate    
----                              END
----                  )                                                                                               AS ToDate,
                  
----                  WAC.CreatedDateTime                                                                       AS MovementDate,
----                  WAC.Id																					     AS WACId,		
----                  POS.ExpiryDate                                                                   AS ExpiryDate,
----                  SUom.Title                                                                                              AS Uom,
                  
----                  WAC.WeightedAverageCost                                                             AS Wac,
----                  (CASE 
----                        WHEN WAC.SourceTypeId = 49 AND WAC.IsReceipt = 0 THEN
----                              SLM.Title
----                        ELSE
----                              ''
----                        END
----                   )                                                                                AS FromLocation,
----                   ''                                                                               AS ToLocation,
----                  (CASE 
----                        WHEN WAC.IsReceipt = 0 THEN 
----                              WAC.Quantity END
----                  )                                                                                               AS QtyOut,
                  
----                  (CASE 
----                        WHEN WAC.IsReceipt = 1 THEN 
----                              WAC.Quantity END
----                  )                                                                                               AS QtyIn,
                  
----                 (CASE 
----					WHEN @rLocationId <> 0 THEN
----						WAC.StoreLocationClosingQuantity
----					ELSE
----						WAC.ClosingQuantity
----					END
----				  )		AS QtyBalance, 
----                  (CASE 
----					WHEN @rLocationId <> 0 THEN
----						(ROUND(WAC.WeightedAverageCost, 2) * WAC.StoreLocationClosingQuantity)
----					ELSE
----						(ROUND(WAC.WeightedAverageCost, 2) * WAC.ClosingQuantity)
----					END
----				  )		AS AmountBalance, 
                  
----                 (CASE 
----					WHEN (@rId <> 0) THEN
----						@lMainGroupCode
----					ELSE
----						SIM.MainGroupCode															 
----					END
----				  )																								AS MainGroupCode, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lMainGroupTitle
----					ELSE
----						SIM.MainGroupTitle															 
----					END
----				  )																								AS MainGroupTitle, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lSubGroupCode
----					ELSE
----						SIM.SubGroupCode															 
----					END
----				  )																								AS SubGroupCode, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lSubGroupTitle
----					ELSE
----						SIM.SubGroupTitle															 
----					END
----				  )																								AS SubGroupTitle, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lStockItemCode
----					ELSE
----						SIM.StockItemCode															 
----					END
----				  )																								AS StockItemCode, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lStockItemTitle
----					ELSE
----						SIM.StockItemTitle															 
----					END
----				  )		   AS StockItemTitle,
----				    0 AS openingbalance
                  
                  
----      FROM  sIp.tWeightedAverageCostLog AS WAC
----                  INNER JOIN sIp.tStoreLocationMaster SLM
----                        ON WAC.StoreLocationId = SLM.Id 
----                  --INNER JOIN sCommon.tSourceTypeMaster STM
----                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
----                  INNER JOIN (SELECT		POSD.Number RefNumber,
----										SB.ExpiryDate ExpiryDate,
----                                        POSD.CreatedDateTime Date,
----                                        POSB.Id
----                              FROM sPharmacy.vExtPointOfSaleBatch POSB
----                                       INNER JOIN sPharmacy.vExtPointOfSaleDetail POSD
----                                            ON POSD.Id = POSB.PointOfSaleDetailId
----                                       --INNER JOIN sPharmacy.vExtPointOfSales POS
----                                       --     ON POS.Id = POSD.PointOfSaleId
----                                       INNER JOIN sProcurement.tStockBatch SB
----                                             ON POSB.StockBatchId = SB.Id ) POS
----                        ON POS.Id = WAC.SourceId AND WAC.SourceTypeId = 49
----                  INNER JOIN  sIp.vExtStockItemMainGroupList SIM
----                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
----                  INNER JOIN sIp.vExtStockItemMaster SIP
----						ON SIM.StockItemId = SIP.Id
----                  INNER JOIN sFinanceCommon.tStockUomMaster SUom
----						ON SIP.IssueStockUomId = SUom.Id
                                    
----WHERE ((WAC.CreatedDateTime >= @rFromDate AND WAC.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
----  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId, 0) = 0))
----  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId, 0) = 0))
----  AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId, 0) = 0))
----  AND WAC.OrgId = @rOrgId    
  
               
--  UNION
 
--      SELECT     SA.RefNumber                                                                   AS RefNo, 
--				 'Stock Adjustment'																				 AS Module,
--				(CASE 
--					WHEN @rLocationId <> 0 THEN
--						@lLocation
--					ELSE
--						'ALL'
--					END
--				)																AS Location, 
				
--				(CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemCode + '-' + @lStockItemTitle
--					ELSE
--						SIM.StockItemCode + '-' + SIM.StockItemTitle															 
--					END
--				)  AS StockItemCodeName, 
--               (CASE
--					WHEN(@rItemMainGroupId <> 0) THEN
--                        @lMainGroupCode + '-' + @lMainGroupTitle
--                    ELSE
--						'ALL'
--					END
--				)    											 AS ItemCodeName, 
--                  (CASE @rFromDate
--                              WHEN '1900/1/1' THEN
--                                    '1900/1/1'
--                              ELSE
--                                    @rFromDate  
--                              END
--                  )                                                                                               AS FromDate,
--                  (CASE @rToDate
--                              WHEN '1900/1/1' THEN
--                                    sCommon.fGetDate()
--                              ELSE
--                                    @rToDate    
--                              END
--                  )                                                                                               AS ToDate,
                  
--                  WAC.CreatedDateTime                                                                       AS MovementDate,
--                  WAC.Id																					     AS WACId,
--                  SA.ExpiryDate                                                                   AS ExpiryDate,
--                  SIP.Uom                                                                                              AS Uom,
                  
--                  WAC.WeightedAverageCost                                                             AS Wac,
--                  (CASE 
--                        WHEN WAC.SourceTypeId = 50 AND WAC.IsReceipt = 0 THEN
--                              SLM.Title
--                        ELSE
--                              ''
--                        END
--                   )                                                                                  AS FromLocation,
--                   ''                                                                              AS ToLocation,
--                  (CASE 
--                        WHEN WAC.IsReceipt = 0 THEN 
--                              WAC.Quantity END
--                  )                                                                                               AS QtyOut,
                  
--                  (CASE 
--                        WHEN WAC.IsReceipt = 1 THEN 
--                              WAC.Quantity END
--                  )                                                                                               AS QtyIn,
                  
--                 (CASE 
--					WHEN @rLocationId <> 0 THEN
--						WAC.StoreLocationClosingQuantity
--					ELSE
--						WAC.ClosingQuantity
--					END
--				  )		AS QtyBalance, 
--                  (CASE 
--					WHEN @rLocationId <> 0 THEN
--						(ROUND(WAC.WeightedAverageCost, 2) * WAC.StoreLocationClosingQuantity)
--					ELSE
--						(ROUND(WAC.WeightedAverageCost, 2) * WAC.ClosingQuantity)
--					END
--				  )		AS AmountBalance, 
                  
--                 (CASE 
--					WHEN (@rId <> 0) THEN
--						@lMainGroupCode
--					ELSE
--						SIM.MainGroupCode															 
--					END
--				  )																								AS MainGroupCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lMainGroupTitle
--					ELSE
--						SIM.MainGroupTitle															 
--					END
--				  )																								AS MainGroupTitle, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lSubGroupCode
--					ELSE
--						SIM.SubGroupCode															 
--					END
--				  )																								AS SubGroupCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lSubGroupTitle
--					ELSE
--						SIM.SubGroupTitle															 
--					END
--				  )																								AS SubGroupTitle, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemCode
--					ELSE
--						SIM.StockItemCode															 
--					END
--				  )																								AS StockItemCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemTitle
--					ELSE
--						SIM.StockItemTitle															 
--					END
--				  )		   AS StockItemTitle,
--				    0 AS openingbalance
                  
                  
--      FROM  sIp.tWeightedAverageCostLog AS WAC
--                  INNER JOIN sIp.tStoreLocationMaster SLM
--                        ON WAC.StoreLocationId = SLM.Id 
--                  --INNER JOIN sCommon.tSourceTypeMaster STM
--                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
--                  INNER JOIN (SELECT		SA.Number RefNumber,
--										SB.ExpiryDate ExpiryDate,
--                                        SA.CreatedDateTime Date,
--                                        SAD.Id
--                              FROM		sProcurement.tStockAdjustmentDetail SAD
--                                       INNER JOIN sProcurement.tStockAdjustment SA
--                                            ON SA.Id = SAD.StockAdjustmentId
--                                        INNER JOIN sProcurement.vExtStockBatch SB
--											ON SAD.StockBatchId = SB.Id AND SAD.OrgId = @rOrgId ) SA
--                        ON SA.Id = WAC.SourceId AND WAC.SourceTypeId = 50
--                INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
--                INNER JOIN (SELECT SIP.Id, SIP.IssueStockUomId, SUom.Title Uom
--								FROM sIp.vExtStockItemMaster SIP
--									INNER JOIN sFinanceCommon.tStockUomMaster SUom
--										ON SIP.IssueStockUomId = SUom.Id AND SIP.OrgId = @rOrgId )SIP
--						ON SIM.StockItemId = SIP.Id
                                    
--WHERE ((WAC.CreatedDateTime >= @rFromDate AND WAC.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
--  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId, 0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId, 0) = 0))
--  AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId, 0) = 0))
--  AND WAC.OrgId = @rOrgId                         
 
--UNION
 
--      SELECT     SI.RefNumber                                                                   AS RefNo, 
--				 'Stock Issue'																				 AS Module,
--				(CASE 
--					WHEN @rLocationId <> 0 THEN
--						@lLocation
--					ELSE
--						'ALL'
--					END
--				)																AS Location, 
				
--				(CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemCode + '-' + @lStockItemTitle
--					ELSE
--						SIM.StockItemCode + '-' + SIM.StockItemTitle															 
--					END
--				)  AS StockItemCodeName, 
--                (CASE
--					WHEN(@rItemMainGroupId <> 0) THEN
--                        @lMainGroupCode + '-' + @lMainGroupTitle
--                    ELSE
--						'ALL'
--					END
--				)    											 AS ItemCodeName, 
--                  (CASE @rFromDate
--                              WHEN '1900/1/1' THEN
--                                    '1900/1/1'
--                              ELSE
--                                    @rFromDate  
--                              END
--                  )                                                                                               AS FromDate,
--                  (CASE @rToDate
--                              WHEN '1900/1/1' THEN
--                                    sCommon.fGetDate()
--                              ELSE
--                                    @rToDate    
--                              END
--                  )                                                                                               AS ToDate,
                  
--                  WAC.CreatedDateTime                                                                       AS MovementDate,
--				  WAC.Id																					     AS WACId,		                  
--                  SI.ExpiryDate                                                                   AS ExpiryDate,
--                  SIP.Uom                                                                                              AS Uom,
                  
--                  WAC.WeightedAverageCost                                                             AS Wac,
--                  (CASE 
--                        WHEN WAC.SourceTypeId = 51 AND WAC.IsReceipt = 0 THEN
--                              SLM.Title
--                        ELSE
--                              ''
--                        END
--                   )                                                                                    AS FromLocation,
--                   ''                                                                            AS ToLocation,
--                  (CASE 
--                        WHEN WAC.IsReceipt = 0 THEN 
--                              WAC.Quantity END
--                  )                                                                                               AS QtyOut,
                  
--                  (CASE 
--                        WHEN WAC.IsReceipt = 1 THEN 
--                              WAC.Quantity END
--                  )                                                                                               AS QtyIn,
                  
--                 (CASE 
--					WHEN @rLocationId <> 0 THEN
--						WAC.StoreLocationClosingQuantity
--					ELSE
--						WAC.ClosingQuantity
--					END
--				  )		AS QtyBalance, 
--                  (CASE 
--					WHEN @rLocationId <> 0 THEN
--						(ROUND(WAC.WeightedAverageCost, 2) * WAC.StoreLocationClosingQuantity)
--					ELSE
--						(ROUND(WAC.WeightedAverageCost, 2) * WAC.ClosingQuantity)
--					END
--				  )		AS AmountBalance, 
                  
--                  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lMainGroupCode
--					ELSE
--						SIM.MainGroupCode															 
--					END
--				  )																								AS MainGroupCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lMainGroupTitle
--					ELSE
--						SIM.MainGroupTitle															 
--					END
--				  )																								AS MainGroupTitle, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lSubGroupCode
--					ELSE
--						SIM.SubGroupCode															 
--					END
--				  )																								AS SubGroupCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lSubGroupTitle
--					ELSE
--						SIM.SubGroupTitle															 
--					END
--				  )																								AS SubGroupTitle, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemCode
--					ELSE
--						SIM.StockItemCode															 
--					END
--				  )																								AS StockItemCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemTitle
--					ELSE
--						SIM.StockItemTitle															 
--					END
--				  )		   AS StockItemTitle,
--				    0 AS openingbalance
                  
                  
--      FROM  sIp.tWeightedAverageCostLog AS WAC
--                  INNER JOIN sIp.tStoreLocationMaster SLM
--                        ON WAC.StoreLocationId = SLM.Id 
--                  --INNER JOIN sCommon.tSourceTypeMaster STM
--                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
--                  INNER JOIN (SELECT		SI.Number RefNumber,
--										SB.ExpiryDate ExpiryDate,
--                                        SI.CreatedDateTime Date,
--                                        SIB.Id
--                              FROM		sProcurement.tStockIssueBatch SIB
--                                       INNER JOIN sProcurement.tStockIssueDetail SID
--                                            ON SID.Id = SIB.StockIssueDetailId
--                                       INNER JOIN sProcurement.tStockIssue SI
--                                            ON SI.Id = SID.StockIssueId
--                                       INNER JOIN sProcurement.vExtStockBatch SB
--											ON SIB.StockBatchId = SB.Id AND SIB.OrgId = @rOrgId
--                                       ) SI
--                        ON SI.Id = WAC.SourceId AND WAC.SourceTypeId = 51
--                INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
--                INNER JOIN (SELECT SIP.Id, SIP.IssueStockUomId, SUom.Title Uom
--								FROM sIp.vExtStockItemMaster SIP
--									INNER JOIN sFinanceCommon.tStockUomMaster SUom
--										ON SIP.IssueStockUomId = SUom.Id AND SIP.OrgId = @rOrgId )SIP
--						ON SIM.StockItemId = SIP.Id                
--WHERE ((WAC.CreatedDateTime >= @rFromDate AND WAC.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
--  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId, 0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId, 0) = 0))
--  AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId, 0) = 0))
--  AND WAC.OrgId = @rOrgId    
                  
--UNION
 
--      SELECT     ST.RefNumber                                                                   AS RefNo, 
--				 'Stock Transfer'																				 AS Module,
--				(CASE 
--					WHEN @rLocationId <> 0 THEN
--						@lLocation
--					ELSE
--						'ALL'
--					END
--				)																AS Location,
			
--				(CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemCode + '-' + @lStockItemTitle
--					ELSE
--						SIM.StockItemCode + '-' + SIM.StockItemTitle															 
--					END
--				)  AS StockItemCodeName, 
--               (CASE
--					WHEN(@rItemMainGroupId <> 0) THEN
--                        @lMainGroupCode + '-' + @lMainGroupTitle
--                    ELSE
--						'ALL'
--					END
--				)    											 AS ItemCodeName, 
--                  (CASE @rFromDate
--                              WHEN '1900/1/1' THEN
--                                    '1900/1/1'
--                              ELSE
--                                    @rFromDate  
--                              END
--                  )                                                                                               AS FromDate,
--                  (CASE @rToDate
--                              WHEN '1900/1/1' THEN
--                                    sCommon.fGetDate()
--                              ELSE
--                                    @rToDate    
--                              END
--                  )                                                                                               AS ToDate,
                  
--                  WAC.CreatedDateTime																				AS MovementDate,
--				  WAC.Id																					     AS WACId,		                  
--                  ST.ExpiryDate																						 AS ExpiryDate,
--                  SIP.Uom                                                                                              AS Uom,
                  
--                  WAC.WeightedAverageCost																			AS Wac,
--                  SLMFrom.Title																					   AS FromLocation,
--                  SLMTo.Title																					  AS ToLocation,
--                  (CASE 
--                        WHEN WAC.IsReceipt = 0 THEN 
--                              WAC.Quantity END
--                  )                                                                                               AS QtyOut,
                  
--                  (CASE 
--                        WHEN WAC.IsReceipt = 1 THEN 
--                              WAC.Quantity END
--                  )                                                                                               AS QtyIn,
                  
--                  (CASE 
--					WHEN @rLocationId <> 0 THEN
--						WAC.StoreLocationClosingQuantity
--					ELSE
--						WAC.ClosingQuantity
--					END
--				  )		AS QtyBalance, 
--                  (CASE 
--					WHEN @rLocationId <> 0 THEN
--						(ROUND(WAC.WeightedAverageCost, 2) * WAC.StoreLocationClosingQuantity)
--					ELSE
--						(ROUND(WAC.WeightedAverageCost, 2) * WAC.ClosingQuantity)
--					END
--				  )		AS AmountBalance, 
                  
--                 (CASE 
--					WHEN (@rId <> 0) THEN
--						@lMainGroupCode
--					ELSE
--						SIM.MainGroupCode															 
--					END
--				  )																								AS MainGroupCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lMainGroupTitle
--					ELSE
--						SIM.MainGroupTitle															 
--					END
--				  )																								AS MainGroupTitle, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lSubGroupCode
--					ELSE
--						SIM.SubGroupCode															 
--					END
--				  )																								AS SubGroupCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lSubGroupTitle
--					ELSE
--						SIM.SubGroupTitle															 
--					END
--				  )																								AS SubGroupTitle, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemCode
--					ELSE
--						SIM.StockItemCode															 
--					END
--				  )																								AS StockItemCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemTitle
--					ELSE
--						SIM.StockItemTitle															 
--					END
--				  )		   AS StockItemTitle,
--				    0 AS openingbalance
                  
                  
--      FROM  sIp.tWeightedAverageCostLog AS WAC
--                  --INNER JOIN sIp.tStoreLocationMaster SLM
--                  --      ON WAC.StoreLocationId = SLM.Id AND WAC.SourceTypeId = 52
--                  --INNER JOIN sCommon.tSourceTypeMaster STM
--                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
--                  INNER JOIN (SELECT		ST.Number RefNumber,
--										SB.ExpiryDate ExpiryDate,
--                                        ST.CreatedDateTime Date,
--                                        STB.Id,
--                                        ST.FromStoreLocationId,
--                                        ST.ToStoreLocationId
--                              FROM sProcurement.tStockTransferBatch  STB
--                                       INNER JOIN sProcurement.tStockTransferDetail STD
--                                            ON STD.Id = STB.StockTransferDetailId
--                                       INNER JOIN sProcurement.tStockTransfer ST
--                                            ON ST.Id = STD.StockTransferId
--                                       INNER JOIN sProcurement.tStockBatch SB
--                                             ON STB.FromStockBatchId  = SB.Id AND STB.OrgId = @rOrgId) ST
--                        ON ST.Id = WAC.SourceId AND WAC.SourceTypeId = 52
--                 INNER JOIN sIp.tStoreLocationMaster SLMFrom
--                        ON ST.FromStoreLocationId = SLMFrom.Id 
--                 INNER JOIN sIp.tStoreLocationMaster SLMTo
--                        ON ST.ToStoreLocationId = SLMTo.Id
--                 INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
--                INNER JOIN (SELECT SIP.Id, SIP.IssueStockUomId, SUom.Title Uom
--								FROM sIp.vExtStockItemMaster SIP
--									INNER JOIN sFinanceCommon.tStockUomMaster SUom
--										ON SIP.IssueStockUomId = SUom.Id AND SIP.OrgId = @rOrgId )SIP
--						ON SIM.StockItemId = SIP.Id               
--WHERE ((WAC.CreatedDateTime >= @rFromDate AND WAC.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
--  AND ((WAC.StoreLocationId = @rLocationId) OR (ISNULL(@rLocationId, 0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId, 0) = 0))
--  AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId, 0) = 0))
--  AND WAC.OrgId = @rOrgId    
                  

  
----  UNION
 
----      SELECT     OE.RefNumber                                                                   AS RefNo, 
----				 'Order Entry'																				 AS Module,
----				(CASE 
----					WHEN @rLocationId <> 0 THEN
----						@lLocation
----					ELSE
----						'ALL'
----					END
----				)																AS Location, 
				
----				(CASE 
----					WHEN (@rId <> 0) THEN
----						@lStockItemCode + '-' + @lStockItemTitle
----					ELSE
----						SIM.StockItemCode + '-' + SIM.StockItemTitle															 
----					END
----				)  AS StockItemCodeName, 
----               (CASE
----					WHEN(@rItemMainGroupId <> 0) THEN
----                        @lMainGroupCode + '-' + @lMainGroupTitle
----                    ELSE
----						'ALL'
----					END
----				)    											 AS ItemCodeName, 
----                  (CASE @rFromDate
----                              WHEN '1900/1/1' THEN
----                                    '1900/1/1'
----                              ELSE
----                                    @rFromDate  
----                              END
----                  )                                                                                               AS FromDate,
----                  (CASE @rToDate
----                              WHEN '1900/1/1' THEN
----                                    sCommon.fGetDate()
----                              ELSE
----                                    @rToDate    
----                              END
----                  )                                                                                               AS ToDate,
                  
----                  WAC.CreatedDateTime                                                                       AS MovementDate,
----    				WAC.Id																					     AS WACId,		                  
----                  OE.ExpiryDate                                                                   AS ExpiryDate,
----                  SIP.Uom                                                                                              AS Uom,
                  
----                  WAC.WeightedAverageCost                                                             AS Wac,
----                 (CASE 
----                        WHEN WAC.SourceTypeId = 65 AND WAC.IsReceipt = 0 THEN
----                              SLM.Title
----                        ELSE
----                              ''
----                        END
----                 )                                                                                 AS FromLocation,
----                 ''                                                                                AS ToLocation,
----                  (CASE 
----                        WHEN WAC.IsReceipt = 0 THEN 
----                              WAC.Quantity END
----                  )                                                                                               AS QtyOut,
                  
----                  (CASE 
----                        WHEN WAC.IsReceipt = 1 THEN 
----                              WAC.Quantity END
----                  )                                                                                               AS QtyIn,
                  
----                 (CASE 
----					WHEN @rLocationId <> 0 THEN
----						WAC.StoreLocationClosingQuantity
----					ELSE
----						WAC.ClosingQuantity
----					END
----				  )		AS QtyBalance, 
----                  (CASE 
----					WHEN @rLocationId <> 0 THEN
----						(ROUND(WAC.WeightedAverageCost, 2) * WAC.StoreLocationClosingQuantity)
----					ELSE
----						(ROUND(WAC.WeightedAverageCost, 2) * WAC.ClosingQuantity)
----					END
----				  )		AS AmountBalance,  
                  
----                 (CASE 
----					WHEN (@rId <> 0) THEN
----						@lMainGroupCode
----					ELSE
----						SIM.MainGroupCode															 
----					END
----				  )																								AS MainGroupCode, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lMainGroupTitle
----					ELSE
----						SIM.MainGroupTitle															 
----					END
----				  )																								AS MainGroupTitle, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lSubGroupCode
----					ELSE
----						SIM.SubGroupCode															 
----					END
----				  )																								AS SubGroupCode, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lSubGroupTitle
----					ELSE
----						SIM.SubGroupTitle															 
----					END
----				  )																								AS SubGroupTitle, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lStockItemCode
----					ELSE
----						SIM.StockItemCode															 
----					END
----				  )																								AS StockItemCode, 
----				  (CASE 
----					WHEN (@rId <> 0) THEN
----						@lStockItemTitle
----					ELSE
----						SIM.StockItemTitle															 
----					END							  
----				  )		   AS StockItemTitle,
----				    0 AS openingbalance
                  
                  
----      FROM  sIp.tWeightedAverageCostLog AS WAC
----                  INNER JOIN sIp.tStoreLocationMaster SLM
----                        ON WAC.StoreLocationId = SLM.Id 
----                  --INNER JOIN sCommon.tSourceTypeMaster STM
----                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
----                  INNER JOIN (SELECT		BD.BillNumber  RefNumber,
----										SB.ExpiryDate ExpiryDate,
----                                        OE.CreatedDateTime Date,
----                                        OEB.Id
----                              FROM sOrderEntry.vExtOrderEntryBatch OEB
----                                       INNER JOIN sOrderEntry.vExtOrderEntry OE
----                                            ON OE.Id = OEB.OrderEntryId AND OE.OrderSourceScreenId = 1
----                                        INNER JOIN sOrderEntry.vExtBillingDetail BD
----											ON OE.Id = BD.OrderEntryId 										
----          --                             INNER JOIN sOrderEntry.vExtBillingDetail BD
----										--	ON BD.OrderEntryId = OE.Id
----										--INNER JOIN sOrderEntry.vExtBilling B
----										--	ON B.Id = BD.BillingId
----                                       INNER JOIN sProcurement.tStockBatch SB
----                                             ON OEB.BatchSourceId = SB.Id     AND OEB.OrgId = @rOrgId     ) OE
----                        ON OE.Id = WAC.SourceId AND WAC.SourceTypeId = 65
----               INNER JOIN  sIp.vExtStockItemMainGroupList SIM
----                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
----               INNER JOIN (SELECT SIP.Id, SIP.IssueStockUomId, SUom.Title Uom
----								FROM sIp.vExtStockItemMaster SIP
----									INNER JOIN sFinanceCommon.tStockUomMaster SUom
----										ON SIP.IssueStockUomId = SUom.Id   AND SIP.OrgId = @rOrgId    )SIP
----						ON SIM.StockItemId = SIP.Id                     
----WHERE ((WAC.CreatedDateTime >= @rFromDate AND WAC.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
----  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId, 0) = 0))
----  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId, 0) = 0))
----  AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId, 0) = 0))
----    AND WAC.OrgId = @rOrgId    
  
--  UNION
--   SELECT     SA.RefNumber                                                                   AS RefNo, 
--				 'Stock Take Adjustment'																				 AS Module,
--				(CASE 
--					WHEN @rLocationId <> 0 THEN
--						@lLocation
--					ELSE
--						'ALL'
--					END
--				)																AS Location, 
				
--				(CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemCode + '-' + @lStockItemTitle
--					ELSE
--						SIM.StockItemCode + '-' + SIM.StockItemTitle															 
--					END
--				)  AS StockItemCodeName, 
--               (CASE
--					WHEN(@rItemMainGroupId <> 0) THEN
--                        @lMainGroupCode + '-' + @lMainGroupTitle
--                    ELSE
--						'ALL'
--					END
--				)    											 AS ItemCodeName, 
--                  (CASE @rFromDate
--                              WHEN '1900/1/1' THEN
--                                    '1900/1/1'
--                              ELSE
--                                    @rFromDate  
--                              END
--                  )                                                                                               AS FromDate,
--                  (CASE @rToDate
--                              WHEN '1900/1/1' THEN
--                                    sCommon.fGetDate()
--                              ELSE
--                                    @rToDate    
--                              END
--                  )                                                                                               AS ToDate,
                  
--                  WAC.CreatedDateTime                                                                       AS MovementDate,
--                  WAC.Id																					     AS WACId,
--                  SA.ExpiryDate                                                                   AS ExpiryDate,
--                  SIP.Uom                                                                                              AS Uom,
                  
--                  WAC.WeightedAverageCost                                                             AS Wac,
--                  (CASE 
--                        WHEN WAC.SourceTypeId = 50 AND WAC.IsReceipt = 0 THEN
--                              SLM.Title
--                        ELSE
--                              ''
--                        END
--                   )                                                                                  AS FromLocation,
--                   ''                                                                              AS ToLocation,
--                  (CASE 
--                        WHEN WAC.IsReceipt = 0 THEN 
--                              WAC.Quantity END
--                  )                                                                                               AS QtyOut,
                  
--                  (CASE 
--                        WHEN WAC.IsReceipt = 1 THEN 
--                              WAC.Quantity END
--                  )                                                                                               AS QtyIn,
                  
--                 (CASE 
--					WHEN @rLocationId <> 0 THEN
--						WAC.StoreLocationClosingQuantity
--					ELSE
--						WAC.ClosingQuantity
--					END
--				  )		AS QtyBalance, 
--                  (CASE 
--					WHEN @rLocationId <> 0 THEN
--						(ROUND(WAC.WeightedAverageCost, 2) * WAC.StoreLocationClosingQuantity)
--					ELSE
--						(ROUND(WAC.WeightedAverageCost, 2) * WAC.ClosingQuantity)
--					END
--				  )		AS AmountBalance, 
                  
--                 (CASE 
--					WHEN (@rId <> 0) THEN
--						@lMainGroupCode
--					ELSE
--						SIM.MainGroupCode															 
--					END
--				  )																								AS MainGroupCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lMainGroupTitle
--					ELSE
--						SIM.MainGroupTitle															 
--					END
--				  )																								AS MainGroupTitle, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lSubGroupCode
--					ELSE
--						SIM.SubGroupCode															 
--					END
--				  )																								AS SubGroupCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lSubGroupTitle
--					ELSE
--						SIM.SubGroupTitle															 
--					END
--				  )																								AS SubGroupTitle, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemCode
--					ELSE
--						SIM.StockItemCode															 
--					END
--				  )																								AS StockItemCode, 
--				  (CASE 
--					WHEN (@rId <> 0) THEN
--						@lStockItemTitle
--					ELSE
--						SIM.StockItemTitle															 
--					END
--				  )		   AS StockItemTitle,
--				    0 AS openingbalance
                  
                  
--      FROM  sIp.tWeightedAverageCostLog AS WAC
--                  INNER JOIN sIp.tStoreLocationMaster SLM
--                        ON WAC.StoreLocationId = SLM.Id 
--                  --INNER JOIN sCommon.tSourceTypeMaster STM
--                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
--                  INNER JOIN (SELECT		SFA.Number RefNumber,
--										SB.ExpiryDate ExpiryDate,
--                                        SFA.CreatedDateTime Date,
--                                        SFAD.Id
--                              FROM		sProcurement.tStockFreezeAdjustmentDetail SFAD
--                                       INNER JOIN sProcurement.tStockFreezeAdjustment SFA
--                                            ON SFA.Id = SFAD.StockFreezeAdjustmentId
--                                        INNER JOIN sProcurement.vExtStockBatch SB
--											ON SFAD.StockBatchId = SB.Id  AND SFAD.OrgId = @rOrgId ) SA
--                        ON SA.Id = WAC.SourceId AND WAC.SourceTypeId = 104
--                INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
--                INNER JOIN (SELECT SIP.Id, SIP.IssueStockUomId, SUom.Title Uom
--								FROM sIp.vExtStockItemMaster SIP
--									INNER JOIN sFinanceCommon.tStockUomMaster SUom
--										ON SIP.IssueStockUomId = SUom.Id  AND SIP.OrgId = @rOrgId    )SIP
--						ON SIM.StockItemId = SIP.Id
                                    
--WHERE ((WAC.CreatedDateTime >= @rFromDate AND WAC.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
--  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId, 0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId, 0) = 0))
--  AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId, 0) = 0))
--     AND WAC.OrgId = @rOrgId    
-- ) AS WACMain                 
--ORDER BY WACMain.MovementDate, WACMain.WACId  ASC

	SELECT 0
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockPhysicalVerification]...';


GO
ALTER   PROCEDURE [sProcurement].[pRptStockPhysicalVerification]
	@rOrgId int,
	@rStoreLocationId [int],
	@rItemMainGroupId [int] = 0,
	@rItemName [nvarchar](100) = '',
	@rIdList [nvarchar](1000) = '',
	@rRe [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.

	-- DECLARE @tempIdtable TABLE (item VARCHAR(8000))
	
	--IF(@rIdList IS NOT NULL)
	--INSERT INTO @tempIdtable
	--SELECT item FROM sCommon.fnSplit(@rIdList, ':')
	 
	
	-- SELECT  
	--		SB.Number AS BatchNo,
	--		SB.AvailableQuantity AS SystemQuantity,
	--		CASE WHEN @rRe = 1
	--		THEN SV.PhysicalQuantity ELSE NULL END AS PhysicalQuantity,
	--		SF.CreatedUserId,
	--		SF.CreatedDateTime,
	--		SV.UpdatedUserId,
	--		SV.UpdatedDateTime,
	--		SF.StoreLocationId,
	--		SLM.Title AS Location,
	--		sCommon.fReportDateGet(ExpiryDate) AS ExpiryDate,
	--		SIM.Title AS ItemName,
	--		SIM.Code AS ItemCode,
	--		IMGM.Title AS ItemType,
	--		SUoM.Title AS UOM
			
 
	--	 FROM sIp.tStockItemMaster SIM 
	--	 INNER JOIN sProcurement.tStockBatch SB
	--	 ON SB.StockItemId = SIM.Id
	--	 INNER JOIN sIp.tItemSubGroupMaster ISGM
	--	 ON ISGM.Id=SIM.ItemSubGroupId
	--	 INNER JOIN sIp.tItemMainGroupMaster IMGM
	--	 ON IMGM.Id=ISGM.ItemMainGroupId
	--	 INNER JOIN sFinanceCommon.tStockUomMaster SUOM
	--	 ON SIM.IssueStockUomId = SUOM.Id
	--	 INNER JOIN sProcurement.tStockItemFreeze SF
	--	 ON SF.ItemMainGroupId=IMGM.Id
	--	 LEFT JOIN sProcurement.tStockVerification SV 
	--	 ON SV.StockItemFreezeId = SF.Id
	--	 LEFT JOIN sProcurement.tStockVerification SV1
	--	 ON SV1.StockBatchId = SB.Id
	--	 INNER JOIN sIp.tStoreLocationMaster SLM
	--	 ON SF.StoreLocationId = SLM.Id
	     
	--  WHERE ((SF.StoreLocationId = @rStoreLocationId) 
	--   OR ((IMGM.Id = @rItemMainGroupId ) OR (IMGM.Id = 0))) OR (SIM.Title = @rItemName)
	--   OR (SV.Id in (SELECT item FROM @tempIdtable)) AND (SB.StoreLocationId = @rStoreLocationId) 
	--   AND SIM.OrgId = @rOrgId

		 SELECT  
			0 AS BatchNo,
			0 AS SystemQuantity,
			0 AS PhysicalQuantity,
			0 AS CreatedUserId,
			0 AS CreatedDateTime,
			0 AS UpdatedUserId,
			0 AS UpdatedDateTime,
			0 AS StoreLocationId,
			0 AS Location,
			0 AS ExpiryDate,
			0 AS ItemName,
			0 AS ItemCode,
			0 AS ItemType,
			0 AS UOM
	  
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockPhysicalVerificationRetrieve]...';


GO
ALTER   PROCEDURE [sProcurement].[pRptStockPhysicalVerificationRetrieve]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int,
	@rStoreLocationId [int],
	@rItemMainGroupId [int] = 0,
	@rItemName [nvarchar](100) = '',
	@rIdList [nvarchar](1000) = '',
	@rRe [int]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	-- DECLARE @tempIdtable TABLE (item VARCHAR(8000))
	
	--IF(@rIdList IS NOT NULL)
	--INSERT INTO @tempIdtable
	--SELECT item FROM sCommon.fnSplit(@rIdList, ':')
	 	  
	
	-- SELECT  
	--		@rBuilder1 AS Builder1,
	--	    @rBuilder2 AS Builder2,
	--		SB.Number AS BatchNo,
	--		SB.AvailableQuantity AS SystemQuantity,
	--		CASE WHEN @rRe = 1
	--		THEN SV.PhysicalQuantity ELSE NULL END AS PhysicalQuantity,
	--		SF.CreatedUserId,
	--		SF.CreatedDateTime,
	--		SV.UpdatedUserId,
	--		SV.UpdatedDateTime,
	--		SF.StoreLocationId,
	--		SLM.Title AS Location,
	--		SB.ExpiryDate AS ExpiryDate,
	--		SIM.Title AS ItemName,
	--		SIM.Code AS ItemCode,
	--		IMGM.Title AS ItemType,
	--		SUoM.Title AS UOM
			
 
	--	 FROM sIp.tStockItemMaster SIM 
	--	 INNER JOIN sProcurement.tStockBatch SB
	--	 ON SB.StockItemId = SIM.Id AND SB.AvailableQuantity <> 0 AND ((CAST(SB.ExpiryDate AS DATE) >= CAST(sCommon.fGetDate() AS DATE)) OR SB.ExpiryDate IS NULL)
	--	 INNER JOIN sIp.tItemSubGroupMaster ISGM
	--	 ON ISGM.Id=SIM.ItemSubGroupId
	--	 INNER JOIN sIp.tItemMainGroupMaster IMGM
	--	 ON IMGM.Id=ISGM.ItemMainGroupId
	--	 INNER JOIN sFinanceCommon.tStockUomMaster SUOM
	--	 ON SIM.IssueStockUomId = SUOM.Id
	--	 INNER JOIN sProcurement.tStockItemFreeze SF
	--	 ON SF.ItemMainGroupId=IMGM.Id AND SF.StatusId = 140
	--	 LEFT JOIN sProcurement.tStockVerification SV 
	--	 ON SV.StockItemFreezeId = SF.Id AND SV.StockBatchId = SB.Id OR SV.Id in (SELECT item FROM @tempIdtable) AND SV.IsObsolete = 0
	--	 INNER JOIN sIp.tStoreLocationMaster SLM
	--	 ON SF.StoreLocationId = SLM.Id
	     
	--     WHERE (SB.StoreLocationId = @rStoreLocationId) AND (SF.StoreLocationId = @rStoreLocationId)
	--	 AND( (IMGM.Id = @rItemMainGroupId ) OR (ISNULL(@rItemMainGroupId, 0) = 0) ) 
	--     AND ((SIM.Title like @rItemName) OR (ISNULL(@rItemName, '') = '')) 
	--     AND SIM.OrgId = @rOrgId
	--     AND SIM.IsObsolete=0
	--     ORDER BY  SIM.Title

	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			0 AS BatchNo,
			0 AS SystemQuantity,
			0 AS PhysicalQuantity,
			0 AS CreatedUserId,
			0 AS CreatedDateTime,
			0 AS UpdatedUserId,
			0 AS UpdatedDateTime,
			0 AS StoreLocationId,
			0 AS Location,
			0 AS ExpiryDate,
			0 AS ItemName,
			0 AS ItemCode,
			0 AS ItemType,
			0 AS UOM

END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockTransaction]...';


GO
ALTER   PROCEDURE [sProcurement].[pRptStockTransaction]
	@rOrgId int,
	@rLocationId [int] = 0,
	@rFromLocationId [int] = 0,
	@rId [int] = 0,
	@rTransactionType [int] = 0,
	@rIsDetail [int] = 0,
	@rDepartmentId [int] = 0,
	@rFromDate [datetime] = '1900/1/1',
	@rToDate [datetime] = '1900/1/1'
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
--DECLARE @lStockItemCode VARCHAR(20)
--DECLARE @lStockItemTitle VARCHAR(20)
--DECLARE @lLocation VARCHAR(20) 
--DECLARE @lToLocation VARCHAR(20) 


--IF (@rId <> 0)
--      BEGIN            
--            SELECT @lStockItemCode = SIM.StockItemCode  FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId AND OrgId = @rOrgId
--            SELECT @lStockItemTitle = SIM.StockItemTitle  FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId AND OrgId = @rOrgId
--      END         

--SELECT @lLocation = SLM.Title  FROM sIp.tStoreLocationMaster SLM WHERE SLM.Id = @rLocationId  AND OrgId = @rOrgId
--SELECT @lToLocation = SLM.Title  FROM sIp.tStoreLocationMaster SLM WHERE SLM.Id = @rFromLocationId AND OrgId = @rOrgId

--BEGIN 

-- SELECT RefNo, 
--		CAST(Module AS NVARCHAR(30)) AS Module, 
--		Location, 
--		FromDate, 
--		ToDate,  
--		MovementDate,  
--		WACId,  
--		ISNULL(ExpiryDate,  sCommon.fGetDate()) AS ExpiryDate, 
--		Uom,  
--		Wac,  
--		FromLocation,  
--		ToLocation,  
--		QtyOut,  
--		QtyIn,  
--		QtyBalance,  
--		AmountBalance, 
--		ItemName, 
--		StockItemCode, 
--		StockItemTitle, 
--		ReferenceTo, 
--		(CASE @rTransactionType  WHEN 0 THEN 'ALL' 
--				ELSE (SELECT Title FROM sIp.tStockTransactionTypeMaster WHERE id =  @rTransactionType) END) AS TransactionType, 
--				CASE WHEN @rIsDetail = 0 THEN 'Summary' ELSE 'Detail' END AS IsDetail,	
--		(CASE @rDepartmentId WHEN 0 THEN 'ALL' ELSE
--				(SELECT Title FROM sSetup.tDepartmentMaster WHERE Id = @rDepartmentId AND OrgId = @rOrgId ) END) AS IssueDepartment
--		FROM
--		(SELECT     GRN.RefNumber                                AS RefNo, 
--                        'GRN'                                    AS Module, 
--                 (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END) AS Location,                                                      
--                 (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END) AS ItemName, 
--                 (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate, 
--                 (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END) AS ToDate,                    
--                  WAC.CreatedDateTime                                     AS MovementDate,  
--                  WAC.Id                                                  AS WACId, 
--                  GRN.ExpiryDate                                          AS ExpiryDate,  
--                  SIP.Uom                                                 AS Uom,                  
--                  WAC.WeightedAverageCost                                 AS Wac,  
--                  ''                                                      AS FromLocation,  
--                  ''													  AS ReferenceTo, 
--                  (CASE WHEN @rFromLocationId <> 0 THEN @lToLocation ELSE 'ALL' END ) AS ToLocation, 
--                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END ) AS QtyOut, 
--                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END ) AS QtyIn,                   
--                  (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE WAC.ClosingQuantity
--                              END ) AS QtyBalance,  
                              
--                        (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
--                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,             
--                  --(CASE WHEN @rLocationId <> 0 THEN (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
--                  --            ELSE (WAC.WeightedAverageCost * WAC.ClosingQuantity) END) AS AmountBalance,                        
--                          0 AS openingbalance, 
--                   StockItemCode,    
--				   StockItemTitle
				   
--       FROM  sIp.tWeightedAverageCostLog AS WAC
--                  INNER JOIN sIp.tStoreLocationMaster SLM
--                        ON WAC.StoreLocationId = SLM.Id                    
--                  INNER JOIN (SELECT            GRN.Number RefNumber,   
--                                                            GRNB.ExpiryDate ExpiryDate,  
--                                        GRN.DeliveryOrderDate Date,  
--                                        GRNB.Id
                                        
--                               FROM sProcurement.vExtGoodsReceiptNoteBatch GRNB
--                                       INNER JOIN sProcurement.vExtGoodsReceiptNoteDetail GRND
--                                            ON GRND.Id = GRNB.GoodsReceiptNoteDetailId
--                                       INNER JOIN sProcurement.vExtGoodsReceiptNote GRN
--                                            ON GRN.Id = GRND.GoodsReceiptNoteId WHERE GRNB.orgId = @rOrgId ) GRN   
--                                     ON GRN.Id = WAC.SourceId AND WAC.SourceTypeId = 46
--                  INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
--                  INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
--                                                 FROM sIp.vExtStockItemMaster SIP
--                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
--                                                            ON SIP.IssueStockUomId = SUom.Id AND SIP.OrgId = @rOrgId)SIP
--                                    ON SIM.StockItemId = SIP.Id                                   

--WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
--  AND ((SIM.LocationId = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
--  AND ((SLM.Id = @rFromLocationId) OR (ISNULL(@rFromLocationId,  0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
--  AND ((@rTransactionType = 7) OR (ISNULL(@rTransactionType,  0) = 0))
--  AND (@rDepartmentId = 0)
--  AND  WAC.OrgId = @rOrgId
  
--  --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))
                 

--UNION ALL

--       SELECT GRNR.RefNumber                AS RefNo,  
--              'GREN'                        AS Module,  
--                        (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END) AS Location,  
--                (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END) AS ItemName,  
--                  (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate,  
--                  (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END) AS ToDate,  
--                  WAC.CreatedDateTime                   AS MovementDate,  
--                  WAC.Id							    AS WACId,        
--                  GRNR.ExpiryDate                       AS ExpiryDate,  
--                  SIP.Uom                               AS Uom, 
--                  WAC.WeightedAverageCost               AS Wac,  
--                  ''									AS ReferenceTo, 
--                 (CASE WHEN WAC.SourceTypeId = 47 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE 
--                              '' END) AS FromLocation,  
--                  (CASE WHEN @rFromLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation, 
--                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END ) AS QtyOut,  
--                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END ) AS QtyIn,  
--                  (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE WAC.ClosingQuantity
--                              END) AS QtyBalance,  
--                               (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
--                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,                                
--                  --(CASE WHEN @rLocationId <> 0 THEN (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
--                  --            ELSE (WAC.WeightedAverageCost * WAC.ClosingQuantity) END ) AS AmountBalance,  
--                            0 AS openingbalance,  
--                            StockItemCode, 
--                            StockItemTitle     

--       FROM  sIp.tWeightedAverageCostLog AS WAC
--                  INNER JOIN sIp.tStoreLocationMaster SLM
--                        ON WAC.StoreLocationId = SLM.Id 
--                  INNER JOIN (SELECT GRNR.Number RefNumber,  
--                                        GRNB.ExpiryDate ExpiryDate,  
--                                        GRNR.DeliveryOrderDate Date,  
--                                        GRNRB.Id
--                               FROM sProcurement.vExtGoodsReceiptNoteReturnBatch GRNRB
--                                                         INNER JOIN sProcurement.vExtGoodsReceiptNoteReturnDetail GRNRD
--                                            ON GRNRD.Id = GRNRB.GoodsReceiptNoteReturnDetailId
--                                       INNER JOIN sProcurement.vExtGoodsReceiptNoteReturn GRNR
--                                            ON GRNR.Id = GRNRD.GoodsReceiptNoteReturnId
--                                       INNER JOIN sProcurement.vExtGoodsReceiptNoteBatch GRNB
--                                            ON GRNRB.GoodsReceiptNoteBatchId = GRNB.Id
--                                            ) GRNR                                 
--                                     ON GRNR.Id = WAC.SourceId AND WAC.SourceTypeId = 47
--                  INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
--                  INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
--                                                 FROM sIp.vExtStockItemMaster SIP
--                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
--                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
--                                    ON SIM.StockItemId = SIP.Id                                   

--WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
--  AND ((SIM.LocationId = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
--  AND ((SLM.Id = @rFromLocationId) OR (ISNULL(@rFromLocationId,  0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
--  AND ((@rTransactionType = 8) OR (ISNULL(@rTransactionType,  0) = 0))
--  AND (@rDepartmentId = 0)
--  --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))                  




--  UNION ALL 

--      SELECT     SA.RefNumber                            AS RefNo,  
--                         'Stock Adjustment'              AS Module,  

--                        (CASE 
--                              WHEN @rLocationId <> 0 THEN
--                                    @lLocation
--                              ELSE
--                                    'ALL'
--                              END
--                        )                                 AS Location,                         

--               (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END) AS ItemName,  
--               (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate,  
--               (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END) AS ToDate, 
--                  WAC.CreatedDateTime                      AS MovementDate,  
--                  WAC.Id                                   AS WACId,  
--                  SA.ExpiryDate                            AS ExpiryDate,  
--                  SIP.Uom                                  AS Uom,                    
--                  WAC.WeightedAverageCost                  AS Wac, 
--                  ''									   AS ReferenceTo,  
--                  (CASE WHEN WAC.SourceTypeId = 50 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE ''
--                        END ) AS FromLocation,  
--                   (CASE WHEN @rFromLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation,  
--                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END) AS QtyOut, 
--                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END) AS QtyIn,                    
--                 (CASE WHEN @rLocationId <> 0 THEN
--                                    WAC.StoreLocationClosingQuantity
--                              ELSE 
--                                    WAC.ClosingQuantity
--                              END) AS QtyBalance,  
--                  --(CASE WHEN @rLocationId <> 0 THEN
--                  --                  (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
--                  --            ELSE
--                  --                  (WAC.WeightedAverageCost * WAC.ClosingQuantity)
--                  --            END) AS AmountBalance, 
--                   (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
--                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,      
--                            0 AS openingbalance, 
--                            StockItemCode,    
--							StockItemTitle

--       FROM  sIp.tWeightedAverageCostLog AS WAC
--                  INNER JOIN sIp.tStoreLocationMaster SLM
--                        ON WAC.StoreLocationId = SLM.Id 
--                  --INNER JOIN sCommon.tSourceTypeMaster STM
--                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
--                  INNER JOIN (SELECT            SA.Number RefNumber,  
--                                                            SB.ExpiryDate ExpiryDate,  
--                                        SA.CreatedDateTime Date,  
--                                        SAD.Id
--                               FROM        sProcurement.tStockAdjustmentDetail SAD
--                                       INNER JOIN sProcurement.tStockAdjustment SA
--                                            ON SA.Id = SAD.StockAdjustmentId
--                                        INNER JOIN sProcurement.vExtStockBatch SB
--                                                                  ON SAD.StockBatchId = SB.Id) SA
--                        ON SA.Id = WAC.SourceId AND WAC.SourceTypeId = 50
--                INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
--                INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
--                                                 FROM sIp.vExtStockItemMaster SIP
--                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
--                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
--                                    ON SIM.StockItemId = SIP.Id
--WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) )
--  AND ((SIM.LocationId = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
--  AND ((SLM.Id = @rFromLocationId) OR (ISNULL(@rFromLocationId,  0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
--  AND ((@rTransactionType = 9) OR (ISNULL(@rTransactionType,  0) = 0))
--  AND (@rDepartmentId = 0)
--  --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))                             

--UNION ALL 

--      SELECT     SI.RefNumber                            AS RefNo,  
--                         'Stock Inward'              AS Module,  

--                        (CASE 
--                              WHEN @rLocationId <> 0 THEN
--                                    @lLocation
--                              ELSE
--                                    'ALL'
--                              END
--                        )                                 AS Location,                         

--               (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END) AS ItemName,  
--               (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate,  
--               (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END) AS ToDate, 
--                  WAC.CreatedDateTime                      AS MovementDate,  
--                  WAC.Id                                   AS WACId,  
--                  SI.ExpiryDate                            AS ExpiryDate,  
--                  SIP.Uom                                  AS Uom,                    
--                  WAC.WeightedAverageCost                  AS Wac, 
--                  ''									   AS ReferenceTo,  
--                  (CASE WHEN WAC.SourceTypeId = 50 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE ''
--                        END ) AS FromLocation,  
--                   (CASE WHEN @rFromLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation,  
--                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END) AS QtyOut, 
--                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END) AS QtyIn,                    
--                 (CASE WHEN @rLocationId <> 0 THEN
--                                    WAC.StoreLocationClosingQuantity
--                              ELSE 
--                                    WAC.ClosingQuantity
--                              END) AS QtyBalance,  
--                  --(CASE WHEN @rLocationId <> 0 THEN
--                  --                  (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
--                  --            ELSE
--                  --                  (WAC.WeightedAverageCost * WAC.ClosingQuantity)
--                  --            END) AS AmountBalance, 
--                   (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
--                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,      
--                            0 AS openingbalance, 
--                            StockItemCode,    
--							StockItemTitle

--       FROM  sIp.tWeightedAverageCostLog AS WAC
--                  INNER JOIN sIp.tStoreLocationMaster SLM
--                        ON WAC.StoreLocationId = SLM.Id 
--                  --INNER JOIN sCommon.tSourceTypeMaster STM
--                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
--                  INNER JOIN (SELECT  SI.Number RefNumber,  
--                                                            SB.ExpiryDate ExpiryDate,  
--                                        SI.CreatedDateTime Date,  
--                                        SIB.Id
--                               FROM        sProcurement.tStockInwardBatch SIB
--                                       INNER JOIN sProcurement.tStockInwardDetail [SID]
--                                            ON [SID].Id = SIB.StockInwardDetailId
--                                       INNER JOIN sProcurement.tStockInward SI
--                                            ON SI.Id = [SID].StockInwardId
--                                       INNER JOIN sProcurement.vExtStockBatch SB
--                                                                  ON SIB.StockBatchId = SB.Id) SI
--                        ON SI.Id = WAC.SourceId AND WAC.SourceTypeId = 1010
--                INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
--                INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
--                                                 FROM sIp.vExtStockItemMaster SIP
--                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
--                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
--                                    ON SIM.StockItemId = SIP.Id
--WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) )
--  AND ((SIM.LocationId = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
--  AND ((SLM.Id = @rFromLocationId) OR (ISNULL(@rFromLocationId,  0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
--  AND ((@rTransactionType = 11) OR (ISNULL(@rTransactionType,  0) = 0))
--  AND (@rDepartmentId = 0) 

--UNION ALL

--      SELECT     SI.RefNumber                                                       AS RefNo,   
--                         'Stock Issue'                                              AS Module,   

--                        (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END) AS Location,   
--                (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL'	END ) AS ItemName,   
--                  (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate,  
--                  (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END) AS ToDate,                     
--                  WAC.CreatedDateTime									AS MovementDate,   
--                  WAC.Id												AS WACId,  
--                  SI.ExpiryDate											AS ExpiryDate,  
--                  SIP.Uom												AS Uom,  
--                  WAC.WeightedAverageCost								AS Wac,                     
--				  ISNULL(SI.OrganizationDepartmentName, '')				AS ReferenceTo,
--                  (CASE WHEN WAC.SourceTypeId = 51 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE '' END) AS FromLocation,  
--                   (CASE WHEN @rFromLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation,  
--                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END ) AS QtyOut,  
--                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END ) AS QtyIn,                     
--                 (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE
--                                    WAC.ClosingQuantity END ) AS QtyBalance,  
--                                     (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
--                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,      
--                  --(CASE WHEN @rLocationId <> 0 THEN 
--                  --                  (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
--                  --            ELSE (WAC.WeightedAverageCost * WAC.ClosingQuantity) END) AS AmountBalance,   
--                            0 AS openingbalance,  
--                            StockItemCode,     
--							StockItemTitle  
						
							              
                            
--       FROM  sIp.tWeightedAverageCostLog AS WAC
--                  INNER JOIN sIp.tStoreLocationMaster SLM
--                        ON WAC.StoreLocationId = SLM.Id 
--                  --INNER JOIN sCommon.tSourceTypeMaster STM
--                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
--                  INNER JOIN (SELECT SI.Number RefNumber,  ODM.Title OrganizationDepartmentName,   
--                                                            SB.ExpiryDate ExpiryDate,   
--                                        SI.CreatedDateTime Date,   
--                                        SIB.Id,
--                                        ODM.Id DepartmentId
--                               FROM        sProcurement.tStockIssueBatch SIB
--                                       INNER JOIN sProcurement.tStockIssueDetail [SID]
--                                            ON [SID].Id = SIB.StockIssueDetailId
--                                       INNER JOIN sProcurement.tStockIssue SI
--                                            ON SI.Id = [SID].StockIssueId
--									   INNER JOIN sSetup.tDepartmentMaster ODM
--									   ON ODM.Id = SI.ToOrganizationDepartmentId 
--                                       INNER JOIN sProcurement.vExtStockBatch SB
--                                                                  ON SIB.StockBatchId = SB.Id
--                                       ) SI
--                        ON SI.Id = WAC.SourceId AND WAC.SourceTypeId = 51
--                INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
--                INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
--                                                 FROM sIp.vExtStockItemMaster SIP
--                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
--                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
--                                    ON SIM.StockItemId = SIP.Id                
--WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
--  AND ((SIM.LocationId = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
--  AND ((SLM.Id = @rFromLocationId) OR (ISNULL(@rFromLocationId,  0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
--  AND ((@rTransactionType = 1) OR (ISNULL(@rTransactionType,  0) = 0))
--  AND ((SI.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
--  --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))                


--UNION ALL 

--      SELECT     ST.RefNumber   AS RefNo,  

--                         'Stock Transfer'                                     AS Module,  
--                        (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END) AS Location,                                              
--				  (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL'	END) AS ItemName,  
--                  (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate,  
--                  (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate  END) AS ToDate, 
--                  WAC.CreatedDateTime                                       AS MovementDate,  
--                          WAC.Id                                            AS WACId,       
--                  ST.ExpiryDate                                             AS ExpiryDate,  
--                  SIP.Uom                                                   AS Uom,  
--                  WAC.WeightedAverageCost                                   AS Wac,  
--                  SLMFrom.Title                                             AS FromLocation, 
--                  SLMTo.Title												AS ReferenceTo,  
--                  (CASE WHEN @rFromLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation, 
--                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END) AS QtyOut,                    
--                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END) AS QtyIn,                    
--                  (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE WAC.ClosingQuantity
--                              END) AS QtyBalance, 
--                               (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
--                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,       
--                  --(CASE WHEN @rLocationId <> 0 THEN (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
--                  --            ELSE (WAC.WeightedAverageCost * WAC.ClosingQuantity) END) AS AmountBalance, 
--                            0 AS openingbalance, 
--                            StockItemCode,    
--							StockItemTitle

--       FROM  sIp.tWeightedAverageCostLog AS WAC                

--                  INNER JOIN (SELECT ST.Number RefNumber,  
--                                                            SB.ExpiryDate ExpiryDate,  
--                                        ST.CreatedDateTime Date,  
--                                        STB.Id,  
--                                        ST.FromStoreLocationId,  
--                                        ST.ToStoreLocationId
--                                        --SL.Title StoreLocationName
--                               FROM sProcurement.tStockTransferBatch STB
--                                       INNER JOIN sProcurement.tStockTransferDetail STD
--                                            ON STD.Id = STB.StockTransferDetailId
--                                       INNER JOIN sProcurement.tStockTransfer ST
--                                            ON ST.Id = STD.StockTransferId
--										--INNER JOIN sIp.vExtStoreLocation SL
--										--ON SL.Id = ST.ToStoreLocationId                                            
--                                       INNER JOIN sProcurement.tStockBatch SB
--                                             ON STB.FromStockBatchId = SB.Id) ST
--                        ON ST.Id = WAC.SourceId AND WAC.SourceTypeId = 52
--                 INNER JOIN sIp.tStoreLocationMaster SLMFrom
--                        ON ST.FromStoreLocationId = SLMFrom.Id 
--                 INNER JOIN sIp.tStoreLocationMaster SLMTo
--                        ON ST.ToStoreLocationId = SLMTo.Id
--                 INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
--                INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
--                                                 FROM sIp.vExtStockItemMaster SIP
--                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
--                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
--                                    ON SIM.StockItemId = SIP.Id               
--WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))

----  AND ((ST.FromStoreLocationId = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
--AND ((SIM.LocationId = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
--  AND ((ST.FromStoreLocationId = @rFromLocationId) OR (ISNULL(@rFromLocationId,  0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
--  AND ((@rTransactionType = 2) OR (ISNULL(@rTransactionType,  0) = 0))
--  AND (@rDepartmentId = 0)
--  --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))


--  UNION ALL 

--      SELECT     OE.RefNumber                                     AS RefNo,  
--                          'Stock Freeze Adjustment'                 AS Module,  

--                        (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END) AS Location,                    

--               (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END) AS ItemName,  
--               (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate,  
--               (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END) AS ToDate,                    

--                  WAC.CreatedDateTime                          AS MovementDate,  
--                  WAC.Id                                       AS WACId,                    
--                  OE.ExpiryDate                                AS ExpiryDate,  
--                  SIP.Uom                                      AS Uom,  
--                  WAC.WeightedAverageCost                      AS Wac, 
--                  '' AS ReferenceTo, 

--                 (CASE WHEN WAC.SourceTypeId = 1010 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE '' END
--                 )						    AS FromLocation,  
--                 (CASE WHEN @rFromLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation, 
--                 (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END) AS QtyOut, 
--                 (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END)  AS QtyIn,                    
--                 (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE WAC.ClosingQuantity END
--                          )         AS QtyBalance,  
--                           (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
--                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,      

--                  --(CASE 
--                  --            WHEN @rLocationId <> 0 THEN
--                  --                  (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
--                  --            ELSE
--                  --                  (WAC.WeightedAverageCost * WAC.ClosingQuantity)
--                  --            END
--                  --        )         AS AmountBalance,                          
--                               0 AS openingbalance, 
--                               StockItemCode,    
--								StockItemTitle 

--       FROM  sIp.tWeightedAverageCostLog AS WAC
--                  INNER JOIN sIp.tStoreLocationMaster SLM
--                        ON WAC.StoreLocationId = SLM.Id 
--                  --INNER JOIN sCommon.tSourceTypeMaster STM
--                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
--                  INNER JOIN (SELECT	SFA.Number RefNumber,
--										SB.ExpiryDate ExpiryDate,
--                                        SFA.CreatedDateTime Date,
--                                        SFAD.Id
--                              FROM		sProcurement.tStockFreezeAdjustmentDetail SFAD
--                                       INNER JOIN sProcurement.tStockFreezeAdjustment SFA
--                                            ON SFA.Id = SFAD.StockFreezeAdjustmentId
--                                        INNER JOIN sProcurement.vExtStockBatch SB
--											ON SFAD.StockBatchId = SB.Id) OE
--                        ON OE.Id = WAC.SourceId AND WAC.SourceTypeId = 104
--               INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
--               INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
--                                                 FROM sIp.vExtStockItemMaster SIP
--                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
--                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
--                                    ON SIM.StockItemId = SIP.Id                     

--WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
--  AND ((SIM.LocationId = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
--  AND ((SLM.Id = @rFromLocationId) OR (ISNULL(@rFromLocationId,  0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
--  AND ((@rTransactionType = 10) OR (ISNULL(@rTransactionType,  0) = 0))
--  AND (@rDepartmentId = 0)
-- --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))


----  UNION ALL 

----      SELECT     OE.RefNumber                                     AS RefNo,  
----                         'Order Entry'                            AS Module,  

----                        (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END) AS Location,                    

----               (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END) AS ItemName,  
----               (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate,  
----               (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END) AS ToDate,                    

----                  WAC.CreatedDateTime                          AS MovementDate,  
----                        WAC.Id                                 AS WACId,                    
----                  OE.ExpiryDate                                AS ExpiryDate,  
----                  SIP.Uom                                      AS Uom,  
----                  WAC.WeightedAverageCost                      AS Wac, 
----                  '' AS ReferenceTo, 

----                 (CASE WHEN WAC.SourceTypeId = 65 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE '' END
----                 )						    AS FromLocation,  
----                 (CASE WHEN @rFromLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation, 
----                 (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END) AS QtyOut, 
----                 (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END)  AS QtyIn,                    
----                 (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE WAC.ClosingQuantity END
----                          )         AS QtyBalance,  
----                           (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
----                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,      

----                  --(CASE 
----                  --            WHEN @rLocationId <> 0 THEN
----                  --                  (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
----                  --            ELSE
----                  --                  (WAC.WeightedAverageCost * WAC.ClosingQuantity)
----                  --            END
----                  --        )         AS AmountBalance,                          
----                               0 AS openingbalance, 
----                               StockItemCode,    
----								StockItemTitle 

----       FROM  sIp.tWeightedAverageCostLog AS WAC
----                  INNER JOIN sIp.tStoreLocationMaster SLM
----                        ON WAC.StoreLocationId = SLM.Id 
----                  --INNER JOIN sCommon.tSourceTypeMaster STM
----                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
----                  INNER JOIN (SELECT            BD.BillNumber  RefNumber,  
----                                                            SB.ExpiryDate ExpiryDate,  
----                                        OE.CreatedDateTime Date,  
----                                        OEB.Id
----                               FROM sOrderEntry.vExtOrderEntryBatch OEB
----                                       INNER JOIN sOrderEntry.vExtOrderEntry OE
----                                            ON OE.Id = OEB.OrderEntryId AND OE.OrderSourceScreenId = 1
----                                        INNER JOIN sOrderEntry.vExtBillingDetail BD
----                                                                  ON OE.Id = BD.OrderEntryId 

----                                       INNER JOIN sProcurement.tStockBatch SB
----                                             ON OEB.BatchSourceId = SB.Id) OE
----                        ON OE.Id = WAC.SourceId AND WAC.SourceTypeId = 65
----               INNER JOIN  sIp.vExtStockItemMainGroupList SIM
----                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
----               INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
----                                                 FROM sIp.vExtStockItemMaster SIP
----                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
----                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
----                                    ON SIM.StockItemId = SIP.Id                     

----WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
----  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
----  AND ((SLM.Id = @rFromLocationId) OR (ISNULL(@rFromLocationId,  0) = 0))
----  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
----  AND ((@rTransactionType = 6) OR (ISNULL(@rTransactionType,  0) = 0))
----  AND (@rDepartmentId = 0)

--	UNION ALL 

--      SELECT     D.RefNumber                       AS RefNo,  
--                        'PharmacyDispense'         AS Module,  
--                        (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END ) AS Location,   
--               (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END ) AS ItemName,  
--                  (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END ) AS FromDate,  
--                  (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END)                                                           AS ToDate,  
                  
--                  WAC.CreatedDateTime                                         AS MovementDate,  
--                  WAC.Id                                                      AS WACId,         
--                  D.ExpiryDate                                                AS ExpiryDate,  
--                  SIP.Uom                                                     AS Uom,  
--                  WAC.WeightedAverageCost                                     AS Wac, 
--                  ''														  AS ReferenceTo,  

--                  (CASE WHEN WAC.SourceTypeId = 48 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE '' END) AS FromLocation, 
--                    (CASE WHEN @rFromLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation, 
--                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END ) AS QtyOut, 
--                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END) AS QtyIn,                    
--                  (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE WAC.ClosingQuantity
--                              END) AS QtyBalance,  
--                  --(CASE WHEN @rLocationId <> 0 THEN (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
--                  --            ELSE (WAC.WeightedAverageCost * WAC.ClosingQuantity) END) AS AmountBalance,  
--                   (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
--                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,      
--                            0 AS openingbalance, 
--                            StockItemCode,    
--							StockItemTitle      
							            
--       FROM  sIp.tWeightedAverageCostLog AS WAC
--                  INNER JOIN sIp.tStoreLocationMaster SLM
--                        ON WAC.StoreLocationId = SLM.Id         
--                         INNER JOIN (SELECT        P.Number  RefNumber,  
--                                                   SB.ExpiryDate ExpiryDate,  
--                                        DP.CreatedDateTime Date,  
--                                        DB.Id
--                               FROM  sPharmacy.tDispense DP
--                                       INNER JOIN sPharmacy.tDispenseBatch DB
--                                            ON DB.DispenseId=DP.Id  
--                                        INNER JOIN sExamination.tPrescriptionDetail PD ON PD.Id=DP.PrescriptionDetailId
--		INNER JOIN sExamination.tPrescription P ON P.Id=PD.PrescriptionId
--		INNER JOIN sProcurement.tStockBatch SB ON SB.Id=DB.StockBatchId) D
--                        ON D.Id = WAC.SourceId AND WAC.SourceTypeId = 48
--                  INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34       
--                  INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
--                                                 FROM sIp.vExtStockItemMaster SIP
--                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
--                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
--                                    ON SIM.StockItemId = SIP.Id                  
--WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
--  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
--  AND ((SLM.Id = @rFromLocationId) OR (ISNULL(@rFromLocationId,  0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
--  AND ((@rTransactionType = 3) OR (ISNULL(@rTransactionType,  0) = 0))
--  AND (@rDepartmentId = 0)
--  --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))


---- UNION ALL 

----      SELECT     POS.RefNumber                                       AS RefNo,  
----                         'POS'                                       AS Module, 
----                        (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END ) AS Location, 
----                        (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END ) AS ItemName,  
----                  (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END ) AS FromDate,  
----                  (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END ) AS ToDate,  

----                  WAC.CreatedDateTime                         AS MovementDate,  
----                  WAC.Id                                      AS WACId,   
----                  POS.ExpiryDate                              AS ExpiryDate,  
----                  SUom.Title                                  AS Uom, 
----                  WAC.WeightedAverageCost                     AS Wac, 
----                  ''										  AS ReferenceTo,  

----                  (CASE WHEN WAC.SourceTypeId = 49 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE '' END ) AS FromLocation,  
----                  (CASE WHEN @rFromLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation, 
----                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END) AS QtyOut,  
----                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END) AS QtyIn, 
----                 (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE WAC.ClosingQuantity
----                       END) AS QtyBalance,  
----                        (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
----                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,      
----                  --(CASE WHEN @rLocationId <> 0 THEN (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
----                  --            ELSE (WAC.WeightedAverageCost * WAC.ClosingQuantity) END) AS AmountBalance, 
----                            0 AS openingbalance, 
----                            StockItemCode,    
----							StockItemTitle

----       FROM  sIp.tWeightedAverageCostLog AS WAC
----                  INNER JOIN sIp.tStoreLocationMaster SLM
----                        ON WAC.StoreLocationId = SLM.Id 
----                  --INNER JOIN sCommon.tSourceTypeMaster STM
----                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
----                  INNER JOIN (SELECT POSD.Number RefNumber,  
----                                                            SB.ExpiryDate ExpiryDate,  
----                                        POSD.CreatedDateTime Date,  
----                                        POSB.Id
----                               FROM sPharmacy.vExtPointOfSaleBatch POSB
----                                       INNER JOIN sPharmacy.vExtPointOfSaleDetail POSD
----                                            ON POSD.Id = POSB.PointOfSaleDetailId
----                                       --INNER JOIN sPharmacy.vExtPointOfSales POS
----                                       --     ON POS.Id = POSD.PointOfSaleId
----                                       INNER JOIN sProcurement.tStockBatch SB
----                                             ON POSB.StockBatchId = SB.Id) POS
----                        ON POS.Id = WAC.SourceId AND WAC.SourceTypeId = 49
----                  INNER JOIN  sIp.vExtStockItemMainGroupList SIM
----                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
----                  INNER JOIN sIp.vExtStockItemMaster SIP
----                                    ON SIM.StockItemId = SIP.Id
----                  INNER JOIN sFinanceCommon.tStockUomMaster SUom
----                                    ON SIP.IssueStockUomId = SUom.Id  
----WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
----  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
----  AND ((SLM.Id = @rFromLocationId) OR (ISNULL(@rFromLocationId,  0) = 0))
----  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
----  AND ((@rTransactionType = 4) OR (ISNULL(@rTransactionType,  0) = 0))
----  AND (@rDepartmentId = 0)
----  --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))
                  


-- ) AS WACMain   
           
--ORDER BY WACMain.MovementDate,  WACMain.WACId  ASC                  
SELECT	0 AS RefNo, 
		0 AS Module, 
		0 AS Location, 
		0 AS FromDate, 
		0 AS ToDate,  
		0 AS MovementDate,  
		0 AS WACId,  
		0 AS ExpiryDate, 
		0 AS Uom,  
		0 AS Wac,  
		0 AS FromLocation,  
		0 AS ToLocation,  
		0 AS QtyOut,  
		0 AS QtyIn,  
		0 AS QtyBalance,  
		0 AS AmountBalance, 
		0 AS ItemName, 
		0 AS StockItemCode, 
		0 AS StockItemTitle, 
		0 AS ReferenceTo, 
		0 AS IsDetail,	
		0 AS IssueDepartment
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockTransaction_Check]...';


GO
ALTER   PROCEDURE [sProcurement].[pRptStockTransaction_Check]
	@rOrgId int,
	@rLocationId [int] = 0,
	@rToLocationId [int] = 0,
	@rId [int] = 0,
	@rTransactionType [int] = 0,
	@rIsDetail [int] = 0,
	@rDepartmentId [int] = 0,
	@rFromDate [datetime] = '1900/1/1',
	@rToDate [datetime] = '1900/1/1'
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
--DECLARE @lStockItemCode VARCHAR(20)
--DECLARE @lStockItemTitle VARCHAR(20)
--DECLARE @lLocation VARCHAR(20) 
--DECLARE @lToLocation VARCHAR(20) 


--IF (@rId <> 0)
--      BEGIN            
--            SELECT @lStockItemCode = SIM.StockItemCode  FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId AND OrgId = @rOrgId
--            SELECT @lStockItemTitle = SIM.StockItemTitle  FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId AND OrgId = @rOrgId
--      END         

--SELECT @lLocation = SLM.Title  FROM sIp.tStoreLocationMaster SLM WHERE SLM.Id = @rLocationId  AND OrgId = @rOrgId
--SELECT @lToLocation = SLM.Title  FROM sIp.tStoreLocationMaster SLM WHERE SLM.Id = @rToLocationId AND OrgId = @rOrgId

--BEGIN 

-- SELECT RefNo, 
--		CAST(Module AS NVARCHAR(30)) AS Module, 
--		Location, 
--		FromDate, 
--		ToDate,  
--		MovementDate,  
--		WACId,  
--		ISNULL(ExpiryDate,  sCommon.fGetDate()) AS ExpiryDate, 
--		Uom,  
--		Wac,  
--		FromLocation,  
--		ToLocation,  
--		QtyOut,  
--		QtyIn,  
--		QtyBalance,  
--		AmountBalance, 
--		ItemName, 
--		StockItemCode, 
--		StockItemTitle, 
--		ReferenceTo, 
--		(CASE @rTransactionType  WHEN 0 THEN 'ALL' 
--				ELSE (SELECT Title FROM sIp.tStockTransactionTypeMaster WHERE id =  @rTransactionType) END) AS TransactionType, 
--				CASE WHEN @rIsDetail = 0 THEN 'Summary' ELSE 'Detail' END AS IsDetail,	
--		(CASE @rDepartmentId WHEN 0 THEN 'ALL' ELSE
--				(SELECT Title FROM sSetup.tDepartmentMaster WHERE Id = @rDepartmentId AND OrgId = @rOrgId ) END) AS IssueDepartment
--		FROM
--		(
		
		
----		SELECT     GRN.RefNumber                                AS RefNo, 
----                        'GRN'                                    AS Module, 
----                 (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END) AS Location,                                                      
----                 (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END) AS ItemName, 
----                 (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate, 
----                 (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END) AS ToDate,                    
----                  WAC.CreatedDateTime                                     AS MovementDate,  
----                  WAC.Id                                                  AS WACId, 
----                  GRN.ExpiryDate                                          AS ExpiryDate,  
----                  SIP.Uom                                                 AS Uom,                  
----                  WAC.WeightedAverageCost                                 AS Wac,  
----                  ''                                                      AS FromLocation,  
----                  ''													  AS ReferenceTo, 
----                  (CASE WHEN @rToLocationId <> 0 THEN @lToLocation ELSE 'ALL' END ) AS ToLocation, 
----                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END ) AS QtyOut, 
----                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END ) AS QtyIn,                   
----                  (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE WAC.ClosingQuantity
----                              END ) AS QtyBalance,  
                              
----                        (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
----                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,             
----                  --(CASE WHEN @rLocationId <> 0 THEN (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
----                  --            ELSE (WAC.WeightedAverageCost * WAC.ClosingQuantity) END) AS AmountBalance,                        
----                          0 AS openingbalance, 
----                   StockItemCode,    
----				   StockItemTitle
				   
----       FROM  sIp.tWeightedAverageCostLog AS WAC
----                  INNER JOIN sIp.tStoreLocationMaster SLM
----                        ON WAC.StoreLocationId = SLM.Id 
----                  INNER JOIN (SELECT            GRN.Number RefNumber,   
----                                                            GRNB.ExpiryDate ExpiryDate,  
----                                        GRN.DeliveryOrderDate Date,  
----                                        GRNB.Id
                                        
----                               FROM sProcurement.vExtGoodsReceiptNoteBatch GRNB
----                                       INNER JOIN sProcurement.vExtGoodsReceiptNoteDetail GRND
----                                            ON GRND.Id = GRNB.GoodsReceiptNoteDetailId
----                                       INNER JOIN sProcurement.vExtGoodsReceiptNote GRN
----                                            ON GRN.Id = GRND.GoodsReceiptNoteId WHERE GRNB.orgId = @rOrgId ) GRN   
----                                     ON GRN.Id = WAC.SourceId AND WAC.SourceTypeId = 46
----                  INNER JOIN  sIp.vExtStockItemMainGroupList SIM
----                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
----                  INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
----                                                 FROM sIp.vExtStockItemMaster SIP
----                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
----                                                            ON SIP.IssueStockUomId = SUom.Id AND SIP.OrgId = @rOrgId)SIP
----                                    ON SIM.StockItemId = SIP.Id                                   

----WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
----  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
----  AND ((SLM.Id = @rToLocationId) OR (ISNULL(@rToLocationId,  0) = 0))
----  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
----  AND ((@rTransactionType = 7) OR (ISNULL(@rTransactionType,  0) = 0))
----  AND (@rDepartmentId = 0)
----  AND  WAC.OrgId = @rOrgId
  
 
                 

----UNION ALL

----       SELECT GRNR.RefNumber                AS RefNo,  
----              'GREN'                        AS Module,  
----                        (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END) AS Location,  
----                (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END) AS ItemName,  
----                  (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate,  
----                  (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END) AS ToDate,  
----                  WAC.CreatedDateTime                   AS MovementDate,  
----                  WAC.Id							    AS WACId,        
----                  GRNR.ExpiryDate                       AS ExpiryDate,  
----                  SIP.Uom                               AS Uom, 
----                  WAC.WeightedAverageCost               AS Wac,  
----                  ''									AS ReferenceTo, 
----                 (CASE WHEN WAC.SourceTypeId = 47 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE 
----                              '' END) AS FromLocation,  
----                  (CASE WHEN @rToLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation, 
----                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END ) AS QtyOut,  
----                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END ) AS QtyIn,  
----                  (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE WAC.ClosingQuantity
----                              END) AS QtyBalance,  
----                               (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
----                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,                                
----                  --(CASE WHEN @rLocationId <> 0 THEN (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
----                  --            ELSE (WAC.WeightedAverageCost * WAC.ClosingQuantity) END ) AS AmountBalance,  
----                            0 AS openingbalance,  
----                            StockItemCode, 
----                            StockItemTitle     

----       FROM  sIp.tWeightedAverageCostLog AS WAC
----                  INNER JOIN sIp.tStoreLocationMaster SLM
----                        ON WAC.StoreLocationId = SLM.Id 
----                  INNER JOIN (SELECT GRNR.Number RefNumber,  
----                                        GRNB.ExpiryDate ExpiryDate,  
----                                        GRNR.DeliveryOrderDate Date,  
----                                        GRNRB.Id
----                               FROM sProcurement.vExtGoodsReceiptNoteReturnBatch GRNRB
----                                                         INNER JOIN sProcurement.vExtGoodsReceiptNoteReturnDetail GRNRD
----                                            ON GRNRD.Id = GRNRB.GoodsReceiptNoteReturnDetailId
----                                       INNER JOIN sProcurement.vExtGoodsReceiptNoteReturn GRNR
----                                            ON GRNR.Id = GRNRD.GoodsReceiptNoteReturnId
----                                       INNER JOIN sProcurement.vExtGoodsReceiptNoteBatch GRNB
----                                            ON GRNRB.GoodsReceiptNoteBatchId = GRNB.Id
----                                            ) GRNR                                 
----                                     ON GRNR.Id = WAC.SourceId AND WAC.SourceTypeId = 47
----                  INNER JOIN  sIp.vExtStockItemMainGroupList SIM
----                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
----                  INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
----                                                 FROM sIp.vExtStockItemMaster SIP
----                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
----                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
----                                    ON SIM.StockItemId = SIP.Id                                   

----WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
----  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
----  AND ((SLM.Id = @rToLocationId) OR (ISNULL(@rToLocationId,  0) = 0))
----  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
----  AND ((@rTransactionType = 8) OR (ISNULL(@rTransactionType,  0) = 0))
----  AND (@rDepartmentId = 0)
----  --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))                  


----	UNION ALL 

----      SELECT     D.RefNumber                       AS RefNo,  
----                        'PharmacyDispense'         AS Module,  
----                        (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END ) AS Location,   
----               (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END ) AS ItemName,  
----                  (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END ) AS FromDate,  
----                  (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END)                                                           AS ToDate,  
                  
----                  WAC.CreatedDateTime                                         AS MovementDate,  
----                  WAC.Id                                                      AS WACId,         
----                  D.ExpiryDate                                                AS ExpiryDate,  
----                  SIP.Uom                                                     AS Uom,  
----                  WAC.WeightedAverageCost                                     AS Wac, 
----                  ''														  AS ReferenceTo,  

----                  (CASE WHEN WAC.SourceTypeId = 65 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE '' END) AS FromLocation, 
----                    (CASE WHEN @rToLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation, 
----                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END ) AS QtyOut, 
----                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END) AS QtyIn,                    
----                  (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE WAC.ClosingQuantity
----                              END) AS QtyBalance,  
----                  --(CASE WHEN @rLocationId <> 0 THEN (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
----                  --            ELSE (WAC.WeightedAverageCost * WAC.ClosingQuantity) END) AS AmountBalance,  
----                   (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
----                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,      
----                            0 AS openingbalance, 
----                            StockItemCode,    
----							StockItemTitle      
							            
----       FROM  sIp.tWeightedAverageCostLog AS WAC
----                  INNER JOIN sIp.tStoreLocationMaster SLM
----                        ON WAC.StoreLocationId = SLM.Id         
----                         INNER JOIN (SELECT           BD.BillNumber  RefNumber,  
----                                                            SB.ExpiryDate ExpiryDate,  
----                                        OE.CreatedDateTime Date,  
----                                        OEB.Id
----                               FROM sOrderEntry.vExtOrderEntryBatch OEB
----                                       INNER JOIN sOrderEntry.vExtOrderEntry OE
----                                            ON OE.Id = OEB.OrderEntryId AND OE.OrderSourceScreenId = 5
----                                        INNER JOIN sOrderEntry.vExtBillingDetail BD
----                                                                  ON OE.Id = BD.OrderEntryId  
----                                       INNER JOIN sProcurement.tStockBatch SB
----                                             ON OEB.BatchSourceId = SB.Id) D
----                        ON D.Id = WAC.SourceId AND WAC.SourceTypeId = 65
----                  INNER JOIN  sIp.vExtStockItemMainGroupList SIM
----                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34       
----                  INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
----                                                 FROM sIp.vExtStockItemMaster SIP
----                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
----                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
----                                    ON SIM.StockItemId = SIP.Id                  
----WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
----  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
----  AND ((SLM.Id = @rToLocationId) OR (ISNULL(@rToLocationId,  0) = 0))
----  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
----  AND ((@rTransactionType = 3) OR (ISNULL(@rTransactionType,  0) = 0))
----  AND (@rDepartmentId = 0)
----  --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))


---- UNION ALL 

----      SELECT     POS.RefNumber                                       AS RefNo,  
----                         'POS'                                       AS Module, 
----                        (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END ) AS Location, 
----                        (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END ) AS ItemName,  
----                  (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END ) AS FromDate,  
----                  (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END ) AS ToDate,  

----                  WAC.CreatedDateTime                         AS MovementDate,  
----                  WAC.Id                                      AS WACId,   
----                  POS.ExpiryDate                              AS ExpiryDate,  
----                  SUom.Title                                  AS Uom, 
----                  WAC.WeightedAverageCost                     AS Wac, 
----                  ''										  AS ReferenceTo,  

----                  (CASE WHEN WAC.SourceTypeId = 49 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE '' END ) AS FromLocation,  
----                  (CASE WHEN @rToLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation, 
----                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END) AS QtyOut,  
----                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END) AS QtyIn, 
----                 (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE WAC.ClosingQuantity
----                       END) AS QtyBalance,  
----                        (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
----                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,      
----                  --(CASE WHEN @rLocationId <> 0 THEN (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
----                  --            ELSE (WAC.WeightedAverageCost * WAC.ClosingQuantity) END) AS AmountBalance, 
----                            0 AS openingbalance, 
----                            StockItemCode,    
----							StockItemTitle

----       FROM  sIp.tWeightedAverageCostLog AS WAC
----                  INNER JOIN sIp.tStoreLocationMaster SLM
----                        ON WAC.StoreLocationId = SLM.Id 
----                  --INNER JOIN sCommon.tSourceTypeMaster STM
----                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
----                  INNER JOIN (SELECT POSD.Number RefNumber,  
----                                                            SB.ExpiryDate ExpiryDate,  
----                                        POSD.CreatedDateTime Date,  
----                                        POSB.Id
----                               FROM sPharmacy.vExtPointOfSaleBatch POSB
----                                       INNER JOIN sPharmacy.vExtPointOfSaleDetail POSD
----                                            ON POSD.Id = POSB.PointOfSaleDetailId
----                                       --INNER JOIN sPharmacy.vExtPointOfSales POS
----                                       --     ON POS.Id = POSD.PointOfSaleId
----                                       INNER JOIN sProcurement.tStockBatch SB
----                                             ON POSB.StockBatchId = SB.Id) POS
----                        ON POS.Id = WAC.SourceId AND WAC.SourceTypeId = 49
----                  INNER JOIN  sIp.vExtStockItemMainGroupList SIM
----                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
----                  INNER JOIN sIp.vExtStockItemMaster SIP
----                                    ON SIM.StockItemId = SIP.Id
----                  INNER JOIN sFinanceCommon.tStockUomMaster SUom
----                                    ON SIP.IssueStockUomId = SUom.Id  
----WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
----  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
----  AND ((SLM.Id = @rToLocationId) OR (ISNULL(@rToLocationId,  0) = 0))
----  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
----  AND ((@rTransactionType = 4) OR (ISNULL(@rTransactionType,  0) = 0))
----  AND (@rDepartmentId = 0)
----  --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))
                  

----  UNION ALL 

----      SELECT     SA.RefNumber                            AS RefNo,  
----                         'Stock Adjustment'              AS Module,  

----                        (CASE 
----                              WHEN @rLocationId <> 0 THEN
----                                    @lLocation
----                              ELSE
----                                    'ALL'
----                              END
----                        )                                 AS Location,                         

----               (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END) AS ItemName,  
----               (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate,  
----               (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END) AS ToDate, 
----                  WAC.CreatedDateTime                      AS MovementDate,  
----                  WAC.Id                                   AS WACId,  
----                  SA.ExpiryDate                            AS ExpiryDate,  
----                  SIP.Uom                                  AS Uom,                    
----                  WAC.WeightedAverageCost                  AS Wac, 
----                  ''									   AS ReferenceTo,  
----                  (CASE WHEN WAC.SourceTypeId = 50 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE ''
----                        END ) AS FromLocation,  
----                   (CASE WHEN @rToLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation,  
----                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END) AS QtyOut, 
----                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END) AS QtyIn,                    
----                 (CASE WHEN @rLocationId <> 0 THEN
----                                    WAC.StoreLocationClosingQuantity
----                              ELSE 
----                                    WAC.ClosingQuantity
----                              END) AS QtyBalance,  
----                  --(CASE WHEN @rLocationId <> 0 THEN
----                  --                  (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
----                  --            ELSE
----                  --                  (WAC.WeightedAverageCost * WAC.ClosingQuantity)
----                  --            END) AS AmountBalance, 
----                   (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
----                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,      
----                            0 AS openingbalance, 
----                            StockItemCode,    
----							StockItemTitle

----       FROM  sIp.tWeightedAverageCostLog AS WAC
----                  INNER JOIN sIp.tStoreLocationMaster SLM
----                        ON WAC.StoreLocationId = SLM.Id 
----                  --INNER JOIN sCommon.tSourceTypeMaster STM
----                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
----                  INNER JOIN (SELECT            SA.Number RefNumber,  
----                                                            SB.ExpiryDate ExpiryDate,  
----                                        SA.CreatedDateTime Date,  
----                                        SAD.Id
----                               FROM        sProcurement.tStockAdjustmentDetail SAD
----                                       INNER JOIN sProcurement.tStockAdjustment SA
----                                            ON SA.Id = SAD.StockAdjustmentId
----                                        INNER JOIN sProcurement.vExtStockBatch SB
----                                                                  ON SAD.StockBatchId = SB.Id) SA
----                        ON SA.Id = WAC.SourceId AND WAC.SourceTypeId = 50
----                INNER JOIN  sIp.vExtStockItemMainGroupList SIM
----                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
----                INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
----                                                 FROM sIp.vExtStockItemMaster SIP
----                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
----                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
----                                    ON SIM.StockItemId = SIP.Id
----WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) )
----  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
----  AND ((SLM.Id = @rToLocationId) OR (ISNULL(@rToLocationId,  0) = 0))
----  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
----  AND ((@rTransactionType = 9) OR (ISNULL(@rTransactionType,  0) = 0))
----  AND (@rDepartmentId = 0)
----  --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))                             

 

----UNION ALL

--      SELECT     SI.RefNumber                                                       AS RefNo,   
--                         'Stock Issue'                                              AS Module,   

--                        (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END) AS Location,   
--                (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL'	END ) AS ItemName,   
--                  (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate,  
--                  (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END) AS ToDate,                     
--                  WAC.CreatedDateTime									AS MovementDate,   
--                  WAC.Id												AS WACId,  
--                  SI.ExpiryDate											AS ExpiryDate,  
--                  SIP.Uom												AS Uom,  
--                  WAC.WeightedAverageCost								AS Wac,                     
--				  ISNULL(SI.OrganizationDepartmentName, '')				AS ReferenceTo,
--                  (CASE WHEN WAC.SourceTypeId = 51 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE '' END) AS FromLocation,  
--                   (CASE WHEN @rToLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation,  
--                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END ) AS QtyOut,  
--                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END ) AS QtyIn,                     
--                 (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE
--                                    WAC.ClosingQuantity END ) AS QtyBalance,  
--                                     (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
--                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,      
--                  --(CASE WHEN @rLocationId <> 0 THEN 
--                  --                  (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
--                  --            ELSE (WAC.WeightedAverageCost * WAC.ClosingQuantity) END) AS AmountBalance,   
--                            0 AS openingbalance,  
--                            StockItemCode,     
--							StockItemTitle  
						
							              
                            
--       FROM  sIp.tWeightedAverageCostLog AS WAC
--                  INNER JOIN sIp.tStoreLocationMaster SLM
--                        ON WAC.StoreLocationId = SLM.Id 
--                  --INNER JOIN sCommon.tSourceTypeMaster STM
--                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
--                  INNER JOIN (SELECT SI.Number RefNumber,  ODM.Title OrganizationDepartmentName,   
--                                                            SB.ExpiryDate ExpiryDate,   
--                                        SI.CreatedDateTime Date,   
--                                        SIB.Id,
--                                        ODM.Id DepartmentId
--                               FROM        sProcurement.tStockIssueBatch SIB
--                                       INNER JOIN sProcurement.tStockIssueDetail [SID]
--                                            ON [SID].Id = SIB.StockIssueDetailId
--                                       INNER JOIN sProcurement.tStockIssue SI
--                                            ON SI.Id = [SID].StockIssueId
--									   INNER JOIN sSetup.tDepartmentMaster ODM
--									   ON ODM.Id = SI.ToOrganizationDepartmentId 
--                                       INNER JOIN sProcurement.vExtStockBatch SB
--                                                                  ON SIB.StockBatchId = SB.Id
--                                       ) SI
--                        ON SI.Id = WAC.SourceId AND WAC.SourceTypeId = 51
--                INNER JOIN  sIp.vExtStockItemMainGroupList SIM
--                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
--                INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
--                                                 FROM sIp.vExtStockItemMaster SIP
--                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
--                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
--                                    ON SIM.StockItemId = SIP.Id                
--WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
--  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
--  AND ((SLM.Id = @rToLocationId) OR (ISNULL(@rToLocationId,  0) = 0))
--  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
-- AND ((@rTransactionType = 1) OR (ISNULL(@rTransactionType,  0) = 0))
--  AND ((SI.DepartmentId = @rDepartmentId) OR (DepartmentId = 0))
--  --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))                


----UNION ALL 

----      SELECT     ST.RefNumber   AS RefNo,  

----                         'Stock Transfer'                                     AS Module,  
----                        (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END) AS Location,                                              
----				  (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL'	END) AS ItemName,  
----                  (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate,  
----                  (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate  END) AS ToDate, 
----                  WAC.CreatedDateTime                                       AS MovementDate,  
----                          WAC.Id                                            AS WACId,       
----                  ST.ExpiryDate                                             AS ExpiryDate,  
----                  SIP.Uom                                                   AS Uom,  
----                  WAC.WeightedAverageCost                                   AS Wac,  
----                  SLMFrom.Title                                             AS FromLocation, 
----                  SLMTo.Title												AS ReferenceTo,  
----                  (CASE WHEN @rToLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation, 
----                  (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END) AS QtyOut,                    
----                  (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END) AS QtyIn,                    
----                  (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE WAC.ClosingQuantity
----                              END) AS QtyBalance, 
----                               (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
----                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,       
----                  --(CASE WHEN @rLocationId <> 0 THEN (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
----                  --            ELSE (WAC.WeightedAverageCost * WAC.ClosingQuantity) END) AS AmountBalance, 
----                            0 AS openingbalance, 
----                            StockItemCode,    
----							StockItemTitle

----       FROM  sIp.tWeightedAverageCostLog AS WAC                

----                  INNER JOIN (SELECT ST.Number RefNumber,  
----                                                            SB.ExpiryDate ExpiryDate,  
----                                        ST.CreatedDateTime Date,  
----                                        STB.Id,  
----                                        ST.FromStoreLocationId,  
----                                        ST.ToStoreLocationId
----                                        --SL.Title StoreLocationName
----                               FROM sProcurement.tStockTransferBatch STB
----                                       INNER JOIN sProcurement.tStockTransferDetail STD
----                                            ON STD.Id = STB.StockTransferDetailId
----                                       INNER JOIN sProcurement.tStockTransfer ST
----                                            ON ST.Id = STD.StockTransferId
----										--INNER JOIN sIp.vExtStoreLocation SL
----										--ON SL.Id = ST.ToStoreLocationId                                            
----                                       INNER JOIN sProcurement.tStockBatch SB
----                                             ON STB.FromStockBatchId = SB.Id) ST
----                        ON ST.Id = WAC.SourceId AND WAC.SourceTypeId = 52
----                 INNER JOIN sIp.tStoreLocationMaster SLMFrom
----                        ON ST.FromStoreLocationId = SLMFrom.Id 
----                 INNER JOIN sIp.tStoreLocationMaster SLMTo
----                        ON ST.ToStoreLocationId = SLMTo.Id
----                 INNER JOIN  sIp.vExtStockItemMainGroupList SIM
----                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
----                INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
----                                                 FROM sIp.vExtStockItemMaster SIP
----                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
----                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
----                                    ON SIM.StockItemId = SIP.Id               
----WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
----  AND ((ST.FromStoreLocationId = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
----  AND ((ST.ToStoreLocationId = @rToLocationId) OR (ISNULL(@rToLocationId,  0) = 0))
----  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
----  AND ((@rTransactionType = 2) OR (ISNULL(@rTransactionType,  0) = 0))
----  AND (@rDepartmentId = 0)
----  --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))


----  UNION ALL 

----      SELECT     OE.RefNumber                                     AS RefNo,  
----                          'Stock Freeze Adjustment'                 AS Module,  

----                        (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END) AS Location,                    

----               (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END) AS ItemName,  
----               (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate,  
----               (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END) AS ToDate,                    

----                  WAC.CreatedDateTime                          AS MovementDate,  
----                  WAC.Id                                       AS WACId,                    
----                  OE.ExpiryDate                                AS ExpiryDate,  
----                  SIP.Uom                                      AS Uom,  
----                  WAC.WeightedAverageCost                      AS Wac, 
----                  '' AS ReferenceTo, 

----                 (CASE WHEN WAC.SourceTypeId = 65 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE '' END
----                 )						    AS FromLocation,  
----                 (CASE WHEN @rToLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation, 
----                 (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END) AS QtyOut, 
----                 (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END)  AS QtyIn,                    
----                 (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE WAC.ClosingQuantity END
----                          )         AS QtyBalance,  
----                           (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
----                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,      

----                  --(CASE 
----                  --            WHEN @rLocationId <> 0 THEN
----                  --                  (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
----                  --            ELSE
----                  --                  (WAC.WeightedAverageCost * WAC.ClosingQuantity)
----                  --            END
----                  --        )         AS AmountBalance,                          
----                               0 AS openingbalance, 
----                               StockItemCode,    
----								StockItemTitle 

----       FROM  sIp.tWeightedAverageCostLog AS WAC
----                  INNER JOIN sIp.tStoreLocationMaster SLM
----                        ON WAC.StoreLocationId = SLM.Id 
----                  --INNER JOIN sCommon.tSourceTypeMaster STM
----                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
----                  INNER JOIN (SELECT	SFA.Number RefNumber,
----										SB.ExpiryDate ExpiryDate,
----                                        SFA.CreatedDateTime Date,
----                                        SFAD.Id
----                              FROM		sProcurement.tStockFreezeAdjustmentDetail SFAD
----                                       INNER JOIN sProcurement.tStockFreezeAdjustment SFA
----                                            ON SFA.Id = SFAD.StockFreezeAdjustmentId
----                                        INNER JOIN sProcurement.vExtStockBatch SB
----											ON SFAD.StockBatchId = SB.Id) OE
----                        ON OE.Id = WAC.SourceId AND WAC.SourceTypeId = 104
----               INNER JOIN  sIp.vExtStockItemMainGroupList SIM
----                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
----               INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
----                                                 FROM sIp.vExtStockItemMaster SIP
----                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
----                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
----                                    ON SIM.StockItemId = SIP.Id                     

----WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
----  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
----  AND ((SLM.Id = @rToLocationId) OR (ISNULL(@rToLocationId,  0) = 0))
----  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
----  AND ((@rTransactionType = 10) OR (ISNULL(@rTransactionType,  0) = 0))
----  AND (@rDepartmentId = 0)
---- --AND ((SIM.MainGroupId = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId,  0) = 0))


------  UNION ALL 

------      SELECT     OE.RefNumber                                     AS RefNo,  
------                         'Order Entry'                            AS Module,  

------                        (CASE WHEN @rLocationId <> 0 THEN @lLocation ELSE 'ALL' END) AS Location,                    

------               (CASE WHEN (@rId <> 0) THEN @lStockItemTitle ELSE 'ALL' END) AS ItemName,  
------               (CASE @rFromDate WHEN '1900/1/1' THEN '1900/1/1' ELSE @rFromDate END) AS FromDate,  
------               (CASE @rToDate WHEN '1900/1/1' THEN sCommon.fGetDate() ELSE @rToDate END) AS ToDate,                    

------                  WAC.CreatedDateTime                          AS MovementDate,  
------                        WAC.Id                                 AS WACId,                    
------                  OE.ExpiryDate                                AS ExpiryDate,  
------                  SIP.Uom                                      AS Uom,  
------                  WAC.WeightedAverageCost                      AS Wac, 
------                  '' AS ReferenceTo, 

------                 (CASE WHEN WAC.SourceTypeId = 65 AND WAC.IsReceipt = 0 THEN SLM.Title ELSE '' END
------                 )						    AS FromLocation,  
------                 (CASE WHEN @rToLocationId <> 0 THEN @lToLocation ELSE 'ALL' END) AS ToLocation, 
------                 (CASE WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END) AS QtyOut, 
------                 (CASE WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END)  AS QtyIn,                    
------                 (CASE WHEN @rLocationId <> 0 THEN WAC.StoreLocationClosingQuantity ELSE WAC.ClosingQuantity END
------                          )         AS QtyBalance,  
------                           (CASE WHEN WAC.IsReceipt = 0 THEN (WAC.WeightedAverageCost * WAC.Quantity)
------                              ELSE (WAC.WeightedAverageCost * WAC.Quantity) END) AS AmountBalance,      

------                  --(CASE 
------                  --            WHEN @rLocationId <> 0 THEN
------                  --                  (WAC.WeightedAverageCost * WAC.StoreLocationClosingQuantity)
------                  --            ELSE
------                  --                  (WAC.WeightedAverageCost * WAC.ClosingQuantity)
------                  --            END
------                  --        )         AS AmountBalance,                          
------                               0 AS openingbalance, 
------                               StockItemCode,    
------								StockItemTitle 

------       FROM  sIp.tWeightedAverageCostLog AS WAC
------                  INNER JOIN sIp.tStoreLocationMaster SLM
------                        ON WAC.StoreLocationId = SLM.Id 
------                  --INNER JOIN sCommon.tSourceTypeMaster STM
------                  --    ON WAC.SourceTypeId = STM.Id WHERE STM.Id = 49
------                  INNER JOIN (SELECT            BD.BillNumber  RefNumber,  
------                                                            SB.ExpiryDate ExpiryDate,  
------                                        OE.CreatedDateTime Date,  
------                                        OEB.Id
------                               FROM sOrderEntry.vExtOrderEntryBatch OEB
------                                       INNER JOIN sOrderEntry.vExtOrderEntry OE
------                                            ON OE.Id = OEB.OrderEntryId AND OE.OrderSourceScreenId = 1
------                                        INNER JOIN sOrderEntry.vExtBillingDetail BD
------                                                                  ON OE.Id = BD.OrderEntryId 

------                                       INNER JOIN sProcurement.tStockBatch SB
------                                             ON OEB.BatchSourceId = SB.Id) OE
------                        ON OE.Id = WAC.SourceId AND WAC.SourceTypeId = 65
------               INNER JOIN  sIp.vExtStockItemMainGroupList SIM
------                        ON WAC.ItemSourceId = SIM.StockItemId AND WAC.ItemSourceTypeId = 34
------               INNER JOIN (SELECT SIP.Id,  SIP.IssueStockUomId,  SUom.Title Uom
------                                                 FROM sIp.vExtStockItemMaster SIP
------                                                      INNER JOIN sFinanceCommon.tStockUomMaster SUom
------                                                            ON SIP.IssueStockUomId = SUom.Id)SIP
------                                    ON SIM.StockItemId = SIP.Id                     

------WHERE ((WAC.CreatedDateTime > =  @rFromDate AND WAC.CreatedDateTime < =  (@rToDate + 1)) OR (ISNULL(@rFromDate,  '') = '')OR (ISNULL(@rToDate,  sCommon.fGetDate()) = sCommon.fGetDate()))
------  AND ((SLM.Id = @rLocationId) OR (ISNULL(@rLocationId,  0) = 0))
------  AND ((SLM.Id = @rToLocationId) OR (ISNULL(@rToLocationId,  0) = 0))
------  AND ((SIM.StockItemId = @rId) OR (ISNULL(@rId,  0) = 0))
------  AND ((@rTransactionType = 6) OR (ISNULL(@rTransactionType,  0) = 0))
------  AND (@rDepartmentId = 0)



-- ) AS WACMain   
           
--ORDER BY WACMain.MovementDate,  WACMain.WACId  ASC 
SELECT	0 AS RefNo, 
		0 AS Module, 
		0 AS Location, 
		0 AS FromDate, 
		0 AS ToDate,  
		0 AS MovementDate,  
		0 AS WACId,  
		0 AS ExpiryDate, 
		0 AS Uom,  
		0 AS Wac,  
		0 AS FromLocation,  
		0 AS ToLocation,  
		0 AS QtyOut,  
		0 AS QtyIn,  
		0 AS QtyBalance,  
		0 AS AmountBalance, 
		0 AS ItemName, 
		0 AS StockItemCode, 
		0 AS StockItemTitle, 
		0 AS ReferenceTo, 
		0 AS IsDetail,	
		0 AS IssueDepartment                 

END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockTransactionList]...';


GO
ALTER   PROCEDURE [sProcurement].[pRptStockTransactionList]
	
	@rFromDate [datetime] = '1900/1/1',
	@rToDate [datetime] = '1900/1/1',
	@rDepartmentId smallint,
	@rItemName nvarchar(100),
	@rFromLocationId smallint, 
	@rReportTypeId smallint,
	@rTransactionTypeId smallint,
	@rOrgId int,
	@rLocationId int
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
-- IF(@rTransactionTypeId=1)--Issue--
--	BEGIN
--	SELECT
--		SI.Id AS Id,
--		SI.Number AS Number,
--		SIDL.IssuedQuantity AS Quantity,
--		SI.CreatedDateTime AS Dates,		
--		SIM.Title AS Title,
--		@rReportTypeId AS ReportTypeId
		
--	FROM 
--		sProcurement.tStockIssue SI
--		INNER JOIN sProcurement.tStockIssueDetail SIDL ON SIDL.StockIssueId=SI.Id
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIDL.StockItemId
		
--	   WHERE	
			
--	    (SI.OrgId=@rOrgId)
--		AND ((SI.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((SI.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rToDate,'') = ''))
--		AND (SI.ToOrganizationDepartmentId=@rDepartmentId OR @rDepartmentId=0)
--		AND (SI.FromStoreLocationId=@rFromLocationId OR @rFromLocationId=0)
--		AND (SIM.Title = @rItemName OR @rItemName = '')
--		AND (SIM.LocationId=@rLocationId OR @rLocationId=0)
--		ORDER BY SI.CreatedDateTime ASC
--		END
--IF(@rTransactionTypeId=2)--Transfer--
--	BEGIN
--	   SELECT
--		ST.Id AS Id,
--		ST.CreatedDateTime AS Dates,
--		ST.Number AS Number,
--		STD.TransferredQuantity AS Quantity,
--		SIM.Title AS Title,
--		@rReportTypeId AS ReportTypeId
		
--	FROM 
--		sProcurement.tStockTransfer ST
--		INNER JOIN sProcurement.tStockTransferDetail STD ON STD.StockTransferId=ST.Id
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=STD.StockItemId
		 
--	   WHERE	
--		 (ST.OrgId=@rOrgId)
--		AND ((ST.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((ST.CreatedDateTime <= (@rToDate+1)) OR (ISNULL(@rToDate,'') = '')) 
--		AND (ST.FromStoreLocationId=@rFromLocationId OR @rFromLocationId=0)
--		--AND (ST.ToStoreLocationId=@rToLocationId OR @rToLocationId=0)
--		AND (SIM.Title = @rItemName OR @rItemName = '')
--		AND (SIM.LocationId=@rLocationId OR @rLocationId=0)
--		ORDER BY ST.CreatedDateTime ASC
--	END
--IF(@rTransactionTypeId=3)--Dispense--
--	BEGIN
--	    SELECT
--		D.Id AS Id,
--		D.CreatedDateTime AS Dates,
--		P.Number AS Number,
--		DB.Quantity AS Quantity,
--		SIM.Title AS Title,
--		@rReportTypeId AS ReportTypeId
		
--	FROM 
--		sExamination.tExamination E INNER JOIN sExamination.tPrescription P ON P.SourceId = E.Id
--		inner join sExamination.tPrescriptionDetail PD on PD.PrescriptionId = P.Id AND P.IsObsolete = 0
--		inner join sPharmacy.tDispense d on d.PrescriptionDetailId = PD.Id
--		inner join sPharmacy.tDispenseBatch DB On DB.DispenseId = d.Id
--		INNER JOIN sProcurement.tStockBatch SB ON SB.Id=DB.StockBatchId and SB.StockItemId = PD.StockItemId
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SB.StockItemId 
		
--	   WHERE	
--		 (D.OrgId=@rOrgId)
--		AND ((D.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((D.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rToDate,'') = ''))
--		AND ((E.StoreLocationId = @rFromLocationId) OR @rFromLocationId=0)
--		AND ((SIM.Title = @rItemName) OR @rItemName = '')
--		AND ((SIM.LocationId=@rLocationId) OR @rLocationId=0)
--		ORDER BY D.CreatedDateTime ASC
--	END
--IF(@rTransactionTypeId=7)--GRN--
--	BEGIN
--	   SELECT
--		GRN.Id AS Id,
--		GRN.CreatedDateTime AS Dates,
--		GRN.Number AS Number,
--		GRN.Amount,
--		SIM.Title AS Title,
--		GRND.ReceiptQuantity AS Quantity,
--		@rReportTypeId AS ReportTypeId
		
--	FROM 
--		sProcurement.tGoodsReceiptNote GRN
--		INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND ON GRND.GoodsReceiptNoteId=GRN.Id
--		INNER JOIN sProcurement.tPurchaseOrderDetail POD ON POD.Id=GRND.PurchaseOrderDetailId
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=POD.ItemSourceId
			
--	   WHERE	
--		 (GRN.OrgId=@rOrgId)
--		AND ((GRN.DeliveryOrderDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((GRN.DeliveryOrderDate <= (@rToDate+1)) OR (ISNULL(@rToDate,'') = ''))
--		AND (SIM.Title = @rItemName OR @rItemName = '')
--		AND ((GRN.StoreLocationId = @rFromLocationId) OR @rFromLocationId=0)
--		AND (SIM.LocationId=@rLocationId OR @rLocationId=0)
--		ORDER BY GRN.DeliveryOrderDate ASC
--	END		
--IF(@rTransactionTypeId=8)--GREN--
--	BEGIN
--	   SELECT
--		GRNR.Id AS Id,
--		GRNR.CreatedDateTime AS Dates,
--		GRNR.Number AS Number,
--		SIM.Title AS Title,
--		GRNRD.ReturnQuantity AS Quantity,
--		@rReportTypeId AS ReportTypeId
		
--	FROM 
--		sProcurement.tGoodsReceiptNoteReturn GRNR
--		INNER JOIN sProcurement.tGoodsReceiptNoteReturnDetail GRNRD ON GRNRD.GoodsReceiptNoteReturnId=GRNR.Id
--		INNER JOIN sProcurement.tGoodsReceiptNote GRN ON GRN.Id=GRNR.GoodsReceiptNoteId
--		INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND ON GRND.GoodsReceiptNoteId=GRN.Id
--		INNER JOIN sProcurement.tPurchaseOrderDetail POD ON POD.Id=GRND.PurchaseOrderDetailId
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=POD.ItemSourceId
			
--	   WHERE	
--		 (GRNR.OrgId=@rOrgId)
--		AND ((GRNR.ReturnDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((GRNR.ReturnDate <= (@rToDate + 1)) OR (ISNULL(@rToDate,'') = ''))
--		AND ((GRNR.StoreLocationId = @rFromLocationId) OR @rFromLocationId=0)
--		AND (SIM.Title = @rItemName OR @rItemName = '')
--		AND (SIM.LocationId=@rLocationId OR @rLocationId=0)
--		ORDER BY GRN.DeliveryOrderDate ASC
--	END
--IF(@rTransactionTypeId=9)--Adjustment--
--	BEGIN
--	   SELECT
--		SA.Id AS Id,
--		SA.CreatedDateTime AS Dates,
--		SA.Number AS Number,
--		SAD.PhysicalQuantity AS Quantity,
--		SIM.Title AS Title,
--		@rReportTypeId AS ReportTypeId
		
--	FROM 
--		sProcurement.tStockAdjustment SA
--		INNER JOIN sProcurement.tStockAdjustmentDetail SAD ON SAD.StockAdjustmentId=SA.Id
--		INNER JOIN sProcurement.tStockBatch SB ON SB.Id=SAD.StockBatchId
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SB.StockItemId
			
--	   WHERE	
--		(SA.OrgId=@rOrgId)
--		AND ((SA.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((SA.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rToDate,'') = ''))
--		AND (SA.FromStoreLocationId=@rFromLocationId OR @rFromLocationId=0)
--		AND (SIM.Title = @rItemName OR @rItemName = '')
--		AND (SIM.LocationId=@rLocationId OR @rLocationId=0)
--		ORDER BY SA.CreatedDateTime ASC
--	END
--IF(@rTransactionTypeId=10)--StockFreezeAdjustment--
--	BEGIN
--	   SELECT
--		SFA.Id AS Id,
--		SFA.CreatedDateTime AS Dates,
--		SFA.Number AS Number,
--		SFAD.PhysicalQuantity AS Quantity,
--		SIM.Title AS Title
--		,@rReportTypeId AS ReportTypeId
		
--	FROM 
--		sProcurement.tStockFreezeAdjustment SFA
--		INNER JOIN sProcurement.tStockFreezeAdjustmentDetail SFAD ON SFAD.StockFreezeAdjustmentId=SFA.Id
--		INNER JOIN sProcurement.tStockBatch SB ON SB.Id=SFAD.StockBatchId
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SB.StockItemId
			
--	   WHERE	
	   
--	    (SFA.OrgId=@rOrgId)
--		AND ((SFA.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((SFA.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rToDate,'') = ''))
--		AND ((SFAD.StoreLocationId = @rFromLocationId) OR @rFromLocationId=0)
--		AND (SIM.Title = @rItemName OR @rItemName = '')
--		AND (SIM.LocationId=@rLocationId OR @rLocationId=0)
--		ORDER BY SFA.CreatedDateTime ASC
--	END
--IF(@rTransactionTypeId=11)--StockInward--
--	BEGIN
--	   SELECT
--		SI.Id AS Id,
--		SI.CreatedDateTime AS Dates,
--		SI.Number AS Number,
--		SIDL.InwardQuantity AS Quantity,
--		SIM.Title AS Title
--		,@rReportTypeId AS ReportTypeId
		
--	FROM 
--		sProcurement.tStockInward SI 
--		INNER JOIN sProcurement.tStockInwardDetail SIDL ON SIDL.StockInwardId=SI.Id
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIDL.StockItemId
			
--	   WHERE	
	   
--	    (SI.OrgId=@rOrgId)
--		AND ((SI.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((SI.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rToDate,'') = ''))
--		AND ((SI.ToStoreLocationId = @rFromLocationId) OR @rFromLocationId=0)
--		AND (SIM.Title = @rItemName OR @rItemName = '')
--		AND (SIM.LocationId=@rLocationId OR @rLocationId=0)
--		ORDER BY SI.CreatedDateTime ASC
--	END
SELECT
		0 AS Id,
		0 AS Number,
		0 AS Quantity,
		0 AS Dates,		
		0 AS Title,
		0 AS ReportTypeId
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockTransactionType]...';


GO
ALTER   PROCEDURE [sProcurement].[pRptStockTransactionType]
	
	@rFromDate date = null,
	@rToDate date = null,
	@rDepartmentId smallint,
	@rItemName nvarchar(100),
	@rFromLocationId smallint,
	@rToLocationId smallint,
	@rReportTypeId smallint,
	@rTransactionTypeId smallint,
	@rOrgId int
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
-- IF(@rTransactionTypeId=1)
--	BEGIN
--	SELECT
--		GRN.DeliveryOrderDate,
--		GRN.Number,
--		GRN.Amount,
--		SIM.Title,
--		GRND.ReceiptQuantity
		
--	FROM 
--		sProcurement.tGoodsReceiptNote GRN
--		INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND ON GRND.GoodsReceiptNoteId=GRN.Id
--		INNER JOIN sProcurement.tPurchaseOrderDetail POD ON POD.Id=GRND.PurchaseOrderDetailId
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=POD.ItemSourceId
--		INNER JOIN sProcurement.tPurchaseOrder PO ON PO.Id=POD.PurchaseOrderId
--		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=PO.RequestedOrganizationDepartmentId
--		INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id=PO.StoreLocationId
			
--	   WHERE	
			
--	    (GRN.OrgId=@rOrgId)
--		AND ((GRN.DeliveryOrderDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((GRN.DeliveryOrderDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--		AND (ODM.Id=@rDepartmentId OR @rDepartmentId=0)
--		AND (SLM.Id=@rFromLocationId OR @rFromLocationId=0)
--		AND (SLM.Id=@rToLocationId OR @rToLocationId=0)
--		AND (SIM.Title = @rItemName OR @rItemName = '')
--		END
--IF(@rTransactionTypeId=2)
--	BEGIN
--	   SELECT
--		GRN.DeliveryOrderDate,
--		GRN.Number,
--		GRN.Amount,
--		SIM.Title,
--		GRND.ReceiptQuantity
		
--	FROM 
--		sProcurement.tGoodsReceiptNote GRN
--		INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND ON GRND.GoodsReceiptNoteId=GRN.Id
--		INNER JOIN sProcurement.tPurchaseOrderDetail POD ON POD.Id=GRND.PurchaseOrderDetailId
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=POD.ItemSourceId
--		INNER JOIN sProcurement.tPurchaseOrder PO ON PO.Id=POD.PurchaseOrderId
--		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=PO.RequestedOrganizationDepartmentId
--		INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id=PO.StoreLocationId
			
--	   WHERE	
--		 (GRN.OrgId=@rOrgId)
--		AND ((GRN.DeliveryOrderDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((GRN.DeliveryOrderDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--		AND (ODM.Id=@rDepartmentId OR @rDepartmentId=0)
--		AND (SLM.Id=@rFromLocationId OR @rFromLocationId=0)
--		AND (SLM.Id=@rToLocationId OR @rToLocationId=0)
--		AND (SIM.Title = @rItemName OR @rItemName = '')
--	END
--IF(@rTransactionTypeId=3)
--	BEGIN
--	   SELECT
--		GRN.DeliveryOrderDate,
--		GRN.Number,
--		GRN.Amount,
--		SIM.Title,
--		GRND.ReceiptQuantity
		
--	FROM 
--		sProcurement.tGoodsReceiptNote GRN
--		INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND ON GRND.GoodsReceiptNoteId=GRN.Id
--		INNER JOIN sProcurement.tPurchaseOrderDetail POD ON POD.Id=GRND.PurchaseOrderDetailId
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=POD.ItemSourceId
--		INNER JOIN sProcurement.tPurchaseOrder PO ON PO.Id=POD.PurchaseOrderId
--		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=PO.RequestedOrganizationDepartmentId
--		INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id=PO.StoreLocationId
			
--	   WHERE	
--		 (GRN.OrgId=@rOrgId)
--		AND ((GRN.DeliveryOrderDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((GRN.DeliveryOrderDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--		AND (ODM.Id=@rDepartmentId OR @rDepartmentId=0)
--		AND (SLM.Id=@rFromLocationId OR @rFromLocationId=0)
--		AND (SLM.Id=@rToLocationId OR @rToLocationId=0)
--		AND (SIM.Title = @rItemName OR @rItemName = '')
--	END
--IF(@rTransactionTypeId=4)
--	BEGIN
--	   SELECT
--		GRN.DeliveryOrderDate,
--		GRN.Number,
--		GRN.Amount,
--		SIM.Title,
--		GRND.ReceiptQuantity
		
--	FROM 
--		sProcurement.tGoodsReceiptNote GRN
--		INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND ON GRND.GoodsReceiptNoteId=GRN.Id
--		INNER JOIN sProcurement.tPurchaseOrderDetail POD ON POD.Id=GRND.PurchaseOrderDetailId
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=POD.ItemSourceId
--		INNER JOIN sProcurement.tPurchaseOrder PO ON PO.Id=POD.PurchaseOrderId
--		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=PO.RequestedOrganizationDepartmentId
--		INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id=PO.StoreLocationId
			
--	   WHERE	
--		 (GRN.OrgId=@rOrgId)
--		AND ((GRN.DeliveryOrderDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((GRN.DeliveryOrderDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--		AND (ODM.Id=@rDepartmentId OR @rDepartmentId=0)
--		AND (SLM.Id=@rFromLocationId OR @rFromLocationId=0)
--		AND (SLM.Id=@rToLocationId OR @rToLocationId=0)
--		AND (SIM.Title = @rItemName OR @rItemName = '')
--	END		
--IF(@rTransactionTypeId=5)
--	BEGIN
--	   SELECT
--		GRN.DeliveryOrderDate,
--		GRN.Number,
--		GRN.Amount,
--		SIM.Title,
--		GRND.ReceiptQuantity
		
--	FROM 
--		sProcurement.tGoodsReceiptNote GRN
--		INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND ON GRND.GoodsReceiptNoteId=GRN.Id
--		INNER JOIN sProcurement.tPurchaseOrderDetail POD ON POD.Id=GRND.PurchaseOrderDetailId
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=POD.ItemSourceId
--		INNER JOIN sProcurement.tPurchaseOrder PO ON PO.Id=POD.PurchaseOrderId
--		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=PO.RequestedOrganizationDepartmentId
--		INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id=PO.StoreLocationId
			
--	   WHERE	
--		 (GRN.OrgId=@rOrgId)
--		AND ((GRN.DeliveryOrderDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((GRN.DeliveryOrderDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--		AND (ODM.Id=@rDepartmentId OR @rDepartmentId=0)
--		AND (SLM.Id=@rFromLocationId OR @rFromLocationId=0)
--		AND (SLM.Id=@rToLocationId OR @rToLocationId=0)
--		AND (SIM.Title = @rItemName OR @rItemName = '')
--	END
--IF(@rTransactionTypeId=6)
--	BEGIN
--	   SELECT
--		GRN.DeliveryOrderDate,
--		GRN.Number,
--		GRN.Amount,
--		SIM.Title,
--		GRND.ReceiptQuantity
		
--	FROM 
--		sProcurement.tGoodsReceiptNote GRN
--		INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND ON GRND.GoodsReceiptNoteId=GRN.Id
--		INNER JOIN sProcurement.tPurchaseOrderDetail POD ON POD.Id=GRND.PurchaseOrderDetailId
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=POD.ItemSourceId
--		INNER JOIN sProcurement.tPurchaseOrder PO ON PO.Id=POD.PurchaseOrderId
--		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=PO.RequestedOrganizationDepartmentId
--		INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id=PO.StoreLocationId
			
--	   WHERE	
--		(GRN.OrgId=@rOrgId)
--		AND ((GRN.DeliveryOrderDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((GRN.DeliveryOrderDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--		AND (ODM.Id=@rDepartmentId OR @rDepartmentId=0)
--		AND (SLM.Id=@rFromLocationId OR @rFromLocationId=0)
--		AND (SLM.Id=@rToLocationId OR @rToLocationId=0)
--		AND (SIM.Title = @rItemName OR @rItemName = '')
--	END
--IF(@rTransactionTypeId=7)
--	BEGIN
--	   SELECT
--		GRN.DeliveryOrderDate,
--		GRN.Number,
--		GRN.Amount,
--		SIM.Title,
--		GRND.ReceiptQuantity
		
--	FROM 
--		sProcurement.tGoodsReceiptNote GRN
--		INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND ON GRND.GoodsReceiptNoteId=GRN.Id
--		INNER JOIN sProcurement.tPurchaseOrderDetail POD ON POD.Id=GRND.PurchaseOrderDetailId
--		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=POD.ItemSourceId
--		INNER JOIN sProcurement.tPurchaseOrder PO ON PO.Id=POD.PurchaseOrderId
--		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=PO.RequestedOrganizationDepartmentId
--		INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id=PO.StoreLocationId
			
--	   WHERE	
			
--	    (GRN.OrgId=@rOrgId)
--		AND ((GRN.DeliveryOrderDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--		AND ((GRN.DeliveryOrderDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--		AND (ODM.Id=@rDepartmentId OR @rDepartmentId=0)
--		AND (SLM.Id=@rFromLocationId OR @rFromLocationId=0)
--		AND (SLM.Id=@rToLocationId OR @rToLocationId=0)
--		AND (SIM.Title = @rItemName OR @rItemName = '')
--	END
SELECT
		0 AS DeliveryOrderDate,
		0 AS Number,
		0 AS Amount,
		0 AS Title,
		0 AS ReceiptQuantity
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockTransfer]...';


GO
ALTER   PROCEDURE [sProcurement].[pRptStockTransfer]
	@rOrgId int,
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
--SELECT  ST.FromStoreLocationID,
--		ST.ToStoreLocationID,
--		SLM.Title AS TransferedFrom,
--		SLM2.Title AS TransferedTo,
--		ST.TransferredByName,
--		ST.Number,
--		ST.CreatedDateTime,
--		STD.StockItemId,
--		SIM.Title,		 
--		SI.IssuedQuantity,
--		UOM.Title
--		FROM 
--		sProcurement.tStockTransfer ST
--		INNER JOIN sIp.tStoreLocationMaster SLM
--		ON ST.FromStoreLocationId = SLM.Id
--		INNER JOIN sIp.tStoreLocationMaster SLM2
--		ON ST.ToStoreLocationID = SLM2.Id
--		INNER JOIN sProcurement.tStockTransferDetail STD
--		ON ST.Id = STD.StockTransferId
--		INNER JOIN sIp.tStockItemMaster SIM
--		ON STD.StockItemId = SIM.Id
--		INNER JOIN sProcurement.tStockIssueDetail SI
--		ON SIM.Id = SI.StockItemId 
--		INNER JOIN sFinanceCommon.tStockUomMaster UOM
--		ON  SIM.IssueStockUomId = UOM.Id
--		WHERE ST.Id = @rId AND ST.OrgId = @rOrgId
SELECT  0 AS FromStoreLocationID,
		0 AS ToStoreLocationID,
		0 AS TransferedFrom,
		0 AS TransferedTo,
		0 AS TransferredByName,
		0 AS Number,
		0 AS CreatedDateTime,
		0 AS StockItemId,
		0 AS Title,		 
		0 AS IssuedQuantity,
		0 AS Title
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptTransferAdvice]...';


GO
ALTER   PROCEDURE [sProcurement].[pRptTransferAdvice]
	@rOrgId int,
	@rTransferNo [nvarchar](20) = '',
	@rTransferId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
--SET @rTransferNo	 = 	ISNULL((@rTransferNo), '')

--SELECT		DISTINCT ST.Number 	AS TransferNumber,
--			SLMFrom.Title AS TransferredFromLoc, 
--			SLMTo.Title AS TransferredToLoc, 
--			ST.CreatedDateTime		AS TransferDate, 
--			ST.CreatedDateTime AS TransferTime, 
--			STD.Remark	AS OtherReference, 
--			--STD.StockItemId	AS ItemCode, 
--			vSIM.Code	AS ItemCode, 
--			vSIM.Title  AS ItemDescription, 
--			SUoM.Title  AS Uom, 
--			ISNULL(STD.RequestedQuantity, '0') AS	RequestedQty, 
--			ISNULL(STD.TransferredQuantity, '0') AS	TransferredQty, 
--			ST.TransferredByName AS TransferredByName
			
						
--  FROM sProcurement.tStockTransfer ST
--		INNER JOIN	sProcurement.tStockTransferDetail STD
--			ON	STD.StockTransferId = ST.Id
--		INNER JOIN sIp.tStoreLocationMaster SLMFrom
--			ON ST.FromStoreLocationId = SLMFrom.Id
--		INNER JOIN sIp.tStoreLocationMaster SLMTo
--			ON ST.ToStoreLocationId = SLMTo.Id
--		INNER JOIN sIp.vExtStockItemMaster vSIM
--			ON STD.StockItemId = vSIM.Id
			
--		LEFT JOIN sProcurement.tStockTransferRequestDetail STRD
--			--ON STRD.StockItemId = vSIM.Id
--			ON STRD.StockTransferRequestId = ST.StockTransferRequestId 
--			AND STRD.StockItemId = STD.StockItemId 
--		INNER JOIN	sFinanceCommon.tStockUomMaster SUoM
--				ON SUoM .Id = vSIM.IssueStockUomId
  	
--WHERE	((ST.Number = @rTransferNo) OR (ISNULL(@rTransferNo, '') = '')) AND
--		((ST.Id = @rTransferId) OR (ISNULL(@rTransferId, 0) = 0))
--		 AND ST.OrgId = @rOrgId

		 SELECT		
			0 AS TransferNumber,
			0 AS TransferredFromLoc, 
			0 AS TransferredToLoc, 
			0 AS TransferDate, 
			0 AS TransferTime, 
			0 AS OtherReference, 
			0 AS ItemCode, 
			0 AS ItemDescription, 
			0 AS Uom, 
			0 AS RequestedQty, 
			0 AS TransferredQty, 
			0 AS TransferredByName
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockApprovalModifyUnFreezeGet]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockApprovalModifyUnFreezeGet]
	@rOrgId int,
	@rLocationId [int] = 0,
	@rItemMainGroupId [int] = 0,
	@rCreatedUserId [bigint] = 0,
	@rResult [int] = 0 OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--DECLARE @lBeforeApprovalCount INT
	--DECLARE @lAfterApprovalCount INT

	 

	--SELECT @lBeforeApprovalCount = COUNT(*) FROM sIp.tStockItemMaster SIM 
	--	 INNER JOIN sProcurement.tStockBatch SB
	--	 ON SB.StockItemId = SIM.Id AND ((CAST(SB.ExpiryDate AS DATE) >= CAST(sCommon.fGetDate() AS DATE)) OR (SB.ExpiryDate IS NULL))  AND SB.AvailableQuantity <> 0 
	--	 INNER JOIN sIp.tItemSubGroupMaster ISGM
	--	 ON ISGM.Id=SIM.ItemSubGroupId
	--	 INNER JOIN sIp.tItemMainGroupMaster IMGM
	--	 ON IMGM.Id=ISGM.ItemMainGroupId
	--	 INNER JOIN sProcurement.tStockItemFreeze SF
	--	 ON SF.ItemMainGroupId = IMGM.Id AND SF.StatusId = 140
	--	 INNER JOIN sIp.tStoreLocationMaster SLM
	--	 ON SB.StoreLocationId = SLM.Id	     
	-- WHERE (SB.StoreLocationId = @rLocationId) AND (SF.StoreLocationId = @rLocationId) AND (IMGM.Id = @rItemMainGroupId) 
	-- AND SB.OrgId = @rOrgId AND SIM.IsObsolete=0

	----SELECT @lBeforeApprovalCount

	--SELECT @lAfterApprovalCount = COUNT(*) FROM sProcurement.tStockVerificationApproval SVA
	--	INNER JOIN sProcurement.tStockVerification SV
	--	ON SVA.StockVerificationId = SV.Id AND SV.IsObsolete = 0
	--	INNER JOIN sProcurement.tStockBatch SB 
	--	ON SV.StockBatchId  = SB.Id AND ((CAST(SB.ExpiryDate AS DATE) >= CAST(sCommon.fGetDate() AS DATE)) OR (SB.ExpiryDate IS NULL)) AND SB.AvailableQuantity <> 0 
	--	INNER JOIN sIp.tStockItemMaster SIM
	--	ON SB.StockItemId = SIM.Id
	--	INNER JOIN sIp.tItemSubGroupMaster ISGM
	--	 ON ISGM.Id=SIM.ItemSubGroupId
	--	 INNER JOIN sIp.tItemMainGroupMaster IMGM
	--	 ON IMGM.Id=ISGM.ItemMainGroupId	 
	--	INNER JOIN sProcurement.tStockItemFreeze SF
	--	ON SV.StockItemFreezeId = SF.Id		
	--	INNER JOIN sIp.tStoreLocationMaster SLM
	--	ON SB.StoreLocationId = SLM.Id
	--WHERE (SB.StoreLocationId = @rLocationId) AND (SF.StoreLocationId = @rLocationId) AND (IMGM.Id = @rItemMainGroupId) 
	-- AND SB.OrgId = @rOrgId AND SIM.IsObsolete=0
	
	----select @lAfterApprovalCount
	--If(@lBeforeApprovalCount = @lAfterApprovalCount)
	--BEGIN
	--	SET @rResult  =  1 
		
	--	UPDATE sProcurement.tStockVerification 
	--	SET IsObsolete = 1
	--	WHERE StockItemFreezeId IN (SELECT Id FROM sProcurement.tStockItemFreeze
	--	WHERE StoreLocationId = @rLocationId AND ItemMainGroupId = @rItemMainGroupId AND StatusId = 140 AND OrgId = @rOrgId)
	--	 AND OrgId = @rOrgId
		
		
	--	UPDATE sProcurement.tStockItemFreeze 
	--	SET	StatusId = 141,   --Status ID for unfreeze
	--	UnfreezedBy = @rCreatedUserId,
	--	UnfreezedDateTime = sCommon.fGetDate()
	--	WHERE StoreLocationId = @rLocationId AND ItemMainGroupId = @rItemMainGroupId AND StatusId = 140
	--	AND OrgId = @rOrgId
		
		
		
	--END
	--ELSE
	--	SET @rResult  =  0
		
	--SELECT @rResult AS RESULT
	SELECT 0 AS Result
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockAuditGet]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockAuditGet]
	@rOrgId int,
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	 SELECT 0 AS Id,
			0 AS Number,
			0 AS StoreLocationId,
			0 AS Remark,
			0 AS CreatedUserId,
			0 AS CreatedDateTime
	  -- FROM sProcurement.tStockAudit
	  --WHERE ((Id = @rId) OR (@rId = 0))
	  -- AND OrgId = @rOrgId --Commented as No orgid is there in table
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockBatchWithMainGroupAdd]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockBatchWithMainGroupAdd]
	@rOrgId [int],
	@rItemMainGroupId [int],
	@rStoreLocationId [int],
	@rUserId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SELECT 1 AS Result 
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
--DECLARE @lCounter Int
--DECLARE @lCount Int
--DECLARE @lStockItemId Int

--CREATE TABLE #tStockItemMaster
--	(
--		Id INT IDENTITY(1, 1) PRIMARY KEY,
--		StockItemId INT
--	)

--INSERT INTO #tStockItemMaster(StockItemId)	
--SELECT SIM.Id
--  FROM sIp.tStockItemMaster SIM
--	   INNER JOIN sIp.tItemSubGroupMaster ISGM 
--		       ON SIM.ItemSubGroupId = ISGM.Id
--WHERE ISGM.ItemMainGroupId = @rItemMainGroupId
----AND     SIM.OrgId = @rOrgId --Commented as No orgid is there in table

--SELECT @lCount = MAX(Id) FROM #tStockItemMaster
--SELECT @lCounter = 1

--WHILE (@lCounter <= @lCount)
--	BEGIN
--		SELECT @lStockItemId = StockItemId
--		  FROM #tStockItemMaster
--		 WHERE Id = @lCounter
		 
--		 EXECUTE sProcurement.pStockBatchAdd 
--				@rOrgId= @rOrgId,
--			     @rStoreLocationId = @rStoreLocationId, 
--			     @rStockItemId = @lStockItemId, 
--			     @rNumber = 'Batch 1', 
--			     @rExpiryDate = '2011-01-31', 
--			     @rAvailableQuantity = 2000, 
--			     @rCreatedUserId = @rUserId, 
--			     @rStockBatchId = 0
		 
--		SET @lCounter = @lCounter + 1
--	END
		    
--DROP TABLE #tStockItemMaster
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockFreezeAdjustmentDetailModify]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockFreezeAdjustmentDetailModify]
	@rOrgId [int],
	@rId [int],
	@rStockFreezeAdjustmentId [int],
	@rStockBatchId [int],
	@rStockItemId [int],
	@rStoreLocationId [int],
	@rSystemQuantity [decimal](12, 2),
	@rPhysicalQuantity [decimal](12, 2),
	@rStockVerificationApprovalId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	 --UPDATE sProcurement.tStockFreezeAdjustmentDetail
		--SET 
		--	StockFreezeAdjustmentId = @rStockFreezeAdjustmentId,
		--	StockBatchId = @rStockBatchId,
		--	StockItemId = @rStockItemId,
		--	StoreLocationId = @rStoreLocationId,
		--	SystemQuantity = @rSystemQuantity,
		--	PhysicalQuantity = @rPhysicalQuantity,
		--	StockVerificationApprovalId = @rStockVerificationApprovalId
	 -- WHERE Id = @rId -- AND OrgId =@rOrgId --Commented as No orgid is there in table
	 SELECT 1 AS Result
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockFreezeAdjustmentModify]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockFreezeAdjustmentModify]
	@rOrgId [int],
	@rId [int],
	@rNumber [nvarchar](20)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	 --UPDATE sProcurement.tStockFreezeAdjustment
		--SET 
	 --Number = @rNumber
	 -- WHERE Id = @rId
	  --AND OrgId = @rOrgId  --Commented as No orgid is there in table
	  SELECT 0 As Result
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockVerificationGet]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockVerificationGet]
	@rOrgId [int],
	@rStoreLocationId [int],
	@rItemMainGroupId [int] = 0,
	@rItemName [nvarchar](500) = '',
	@rIdList [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--DECLARE @tempIdtableItemType TABLE (item VARCHAR(8000))
	--DECLARE @tempIdtableStockVerId TABLE (item VARCHAR(8000))
	
	--IF(ISNULL(@rIdList, '') <> '')
	--INSERT INTO @tempIdtableStockVerId  
	----SELECT item FROM sCommon.fnSplit(@rIdList, ':')
	--SELECT DISTINCT item FROM sCommon.fnSplit(@rIdList, ':') WHERE item not like '%#%'
	--INSERT INTO @tempIdtableItemType
	--SELECT DISTINCT item FROM sCommon.fnSplit(@rIdList, '#') WHERE item not like '%:%'
	----SELECT item FROM sCommon.fnSplit('47:48:#106#106', '#') where item not like '%:%'
 --    --SELECT item FROM @tempIdtableStockVerId
	
	SELECT 
			0 AS StockVerificationId,
			0 AS StockItemFreezeId,
			0 AS StockBatchId,
			0 AS BatchNo,
			0 AS SystemQuantity,
			0 AS PhysicalQuantity,
			0 AS CreatedUserId,
			0 AS CreatedDateTime,
			0 AS UpdatedUserId,
			0 AS UpdatedDateTime,
			0 AS StoreLocationId,
			0 AS Location,
			0 AS ExpiryDate,
			0 AS ItemName,
			0 AS ItemCode,
			0 AS ItemMainGroupId,
			0 AS UOM,
			0 AS IsObsolete,
			0 AS ItemMainGroupId,
			0 AS ApprovalStatus

	 --SELECT 
		--	CASE WHEN SV.Id IS NULL
		--	THEN 0 ELSE SV.Id END AS StockVerificationId,
		--	SF.id StockItemFreezeId,
		--	SB.id StockBatchId,
		--	SB.Number AS BatchNo,
		--	SB.AvailableQuantity AS SystemQuantity,
		--	CASE WHEN SV.PhysicalQuantity IS NULL
		--	THEN NULL ELSE SV.PhysicalQuantity END AS PhysicalQuantity,
		--	SF.CreatedUserId,
		--	SV.CreatedDateTime,
		--	SV.UpdatedUserId,
		--	SV.UpdatedDateTime,
		--	SF.StoreLocationId,
		--	SLM.Title AS Location,
		--	SB.ExpiryDate,
		--	SIM.Title AS ItemName,
		--	SIM.Code AS ItemCode,
		--	IMGM.Title AS ItemMainGroupId,
		--	SUoM.Title AS UOM,
		--	SIM.IsObsolete,
		--	SF.ItemMainGroupId,
		--	CASE WHEN SV.Id = SVA.StockVerificationId
		--	THEN 1 ELSE 0 END AS ApprovalStatus
			
 
		-- FROM sIp.tStockItemMaster SIM 
		-- INNER JOIN sProcurement.tStockBatch SB
		-- ON SB.StockItemId = SIM.Id AND SB.AvailableQuantity <> 0 AND ((CAST(SB.ExpiryDate AS DATE) >= CAST(sCommon.fGetDate() AS DATE)) OR SB.ExpiryDate IS NULL) AND SIM.IsObsolete=0
		-- INNER JOIN sIp.tItemSubGroupMaster ISGM
		-- ON ISGM.Id=SIM.ItemSubGroupId
		-- INNER JOIN sIp.tItemMainGroupMaster IMGM
		-- ON IMGM.Id=ISGM.ItemMainGroupId
		-- INNER JOIN sFinanceCommon.tStockUomMaster SUOM
		-- ON SIM.IssueStockUomId = SUOM.Id
		-- INNER JOIN sProcurement.tStockItemFreeze SF
		-- ON SF.ItemMainGroupId = IMGM.Id AND SF.StatusId = 140 AND SF.StoreLocationId=@rStoreLocationId
		-- LEFT JOIN sProcurement.tStockVerification SV 
		-- ON SV.StockItemFreezeId = SF.Id AND SV.StockBatchId = SB.Id 
		-- LEFT JOIN sProcurement.tStockVerificationApproval SVA
		-- ON SVA.StockVerificationId = SV.Id
		-- INNER JOIN sIp.tStoreLocationMaster SLM
		-- ON SF.StoreLocationId = SLM.Id
	     
	 --WHERE (SB.StoreLocationId = @rStoreLocationId)
	 --  AND ((IMGM.Id = @rItemMainGroupId ) OR (ISNULL(@rItemMainGroupId, 0) = 0)
	 --  OR (IMGM.Id IN (SELECT item FROM @tempIdtableItemType))) 
	 --  AND ((SIM.Title = @rItemName) OR (ISNULL(@rItemName, '') = ''))
	 --  OR (SV.Id in (SELECT item FROM @tempIdtableStockVerId))
	 --  AND SV.IsObsolete = 0  
	 --  --AND SIM.OrgId = @rOrgId AND SF.OrgId = @rOrgId--Commented as No orgid is there in table
	 --  ORDER BY  SIM.Title	   
END
GO
PRINT N'Altering Procedure [sProcurement].[pValidateForUnfreeze]...';


GO
ALTER   PROCEDURE [sProcurement].[pValidateForUnfreeze]
	@rStockItemTypeIdList [nvarchar](max),
	@rStoreLocationId [int],
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
		--DECLARE @loIdoc INT				
		--EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockItemTypeIdList
		
		--IF EXISTS(
		--SELECT 
		--		SVA.Id 
		--FROM 
		--		sProcurement.tStockVerificationApproval SVA
		--INNER JOIN 
		--		sProcurement.tStockVerification SV
		--ON		
		--		SVA.StockVerificationId = SV.Id
		--INNER JOIN(SELECT Id FROM sProcurement.tStockItemFreeze SF
		--	WHERE ItemMainGroupId IN (SELECT ItemMainGroupId FROM OPENXML (@loIdoc, '/Root/StockItemTypeId', 1)
		--									WITH
		--										(
		--											ItemMainGroupId INT
		--										)
		--							  ) AND StoreLocationId = @rStoreLocationId 
		--							   --AND SF.OrgId=@rOrgId OR @rOrgId=0 --Commented as No orgid is there in table
		--							   ) SF
		--ON
		--	SF.Id = SV.StockItemFreezeId
		--WHERE SV.IsObsolete = 0)
		--	SELECT 1 AS UnFreeze
		--ELSE
			SELECT 0 AS UnFreeze
			
			
									  
	END
GO
PRINT N'Altering Procedure [sProcurement].[pVendorMasterGet_old]...';


GO
ALTER   PROCEDURE [sProcurement].[pVendorMasterGet_old]
	@rOrgId [int],
	@rId [int] = 0,
	@rTitle [nvarchar](300) = '',
	@rIsWildCardSearch [bit] = 1,
	@rCode [nvarchar](20) = '',
	@rVendorCategoryId [int] = 0,
	@rStartIndex [int] = 0,
	@rPageSize [int] = 0,
	@rLocationId int	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

--Commented on 19/06/2025 - Invalid column name 'OrgId'.

DECLARE @lUpperBound Int
IF @rStartIndex  < 1 SET @rStartIndex = 1 
IF @rPageSize < 1 SET @rPageSize = 1 

SET @lUpperBound = @rStartIndex + @rPageSize 

IF @rIsWildCardSearch = 1
		BEGIN
			
			SET @rCode = sCommon.fSearchStringGet(@rCode)
		END
		
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		
	SELECT 0 AS RowNumber,
		   0 AS Id,
		   0 AS Code,
		   0 AS Title,
		   0 AS IsObsolete,
		   0 AS CreatedUserId,
		   0 AS CreatedDateTime,
		   0 AS UpdatedUserId,
		   0 AS UpdatedDateTime,
		   --Area,
		   --City,
		   0 AS ContactPersonName,
		   --Country,
		   0 AS CreditDays,
		   0 AS CreditLimit,
		   --VM.CreditLimit,
		   0 AS Email,
		   0 AS FaxNumber,		   
		   0 AS PhoneNumberMobile,
	       0 AS PhoneNumberOffice,		   
		   --State,
		   0 AS StreetFour,
		   0 AS StreetOne,
		   0 AS StreetThree,
		   0 AS StreetTwo,
		   0 AS VendorCategoryId,
		   0 AS ZipCode,
		   0 AS VendorCategory,
		   0 AS STATETITLE,
		   0 AS CITYTITLE,
		   0 AS COUNTRYTITLE,
		   0 AS Area,	 
		   0 AS TotalRecords
	--FROM(
	-- SELECT Row_Number() OVER(ORDER BY VM.Id) AS RowNumber,
	--	    VM.Id,
	--		VM.Code,
	--		VM.Title,
	--		VM.IsObsolete,
	--		VM.CreatedUserId,
	--		VM.CreatedDateTime,
	--		VM.UpdatedUserId,
	--		VM.UpdatedDateTime,
	--		--VM.Area,
	--		--VM.City,
	--		VM.ContactPersonName,
	--		--VM.Country,
	--		ISNULL(VM.CreditDays, 0) CreditDays,
	--		ISNULL(CAST(VM.CreditLimit AS DECIMAL(18, 2)), '0') CreditLimit,
	--		--VM.CreditLimit,
	--		VM.Email,
	--		VM.FaxNumber,			
	--		VM.PhoneNumberMobile,
	--		VM.PhoneNumberOffice,			
	--		--VM.State,
	--		VM.StreetFour,
	--		VM.StreetOne,
	--		VM.StreetThree,
	--		VM.StreetTwo,			
	--		VM.VendorCategoryId,
	--		VM.ZipCode,
	--		VC.Title VendorCategory,
	--		VM.State STATETITLE,
	--		VM.City CITYTITLE,
	--		VM.Country COUNTRYTITLE,
	--		VM.Area Area,			
	--		COUNT(*) over() AS TotalRecords
					
					
	--   FROM sProcurement.tVendorMaster  VM 
	--   INNER JOIN   sProcurement.tVendorCategoryMaster VC
	--   ON  VM.VendorCategoryId = VC.Id  
	--   --LEFT JOIN  sCommon.tStateMaster SM 
	--   --ON VM.StateId = SM.Id 
	--   --LEFT JOIN   sCommon.tCityMaster CM 
	--   --ON VM.CityId = CM.Id 
	--   --LEFT JOIN    sCommon.tAreaMaster AM 
	--   --ON VM.AreaId = AM.Id 
	--   --LEFT JOIN   sCommon.tCountryMaster CAM
	--   --ON VM.CountryId = CAM.Id 		     
	--    WHERE ((VM.Id = @rId) OR (@rId = 0))
	--    AND	((VM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	--   AND ((VM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	--    AND ((VM.VendorCategoryId = @rVendorCategoryId) OR (@rVendorCategoryId = 0))
	--    --AND  VM.OrgId = @rOrgId--Commented as No orgid is there in table
	--    AND ((VM.LocationId = @rLocationId) OR (@rLocationId = 0))
	--  -- AND VM.IsObsolete = 0
	--  ) PS
	--	WHERE
	--   PS.RowNumber >= CONVERT(varchar(9), @rStartIndex) AND PS.RowNumber <  CONVERT(varchar(9), @lUpperBound) 
	--   ORDER BY  PS.Id DESC
	   
	 END
GO
PRINT N'Altering Procedure [sSecurity].[pCityListGet]...';


GO
ALTER   PROCEDURE [sSecurity].[pCityListGet]
	@rOrgId int
WITH EXECUTE AS CALLER
AS
--DECLARE @lResult INT
SET NOCOUNT ON
BEGIN
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
SET @rOrgId = 0

		SELECT  
				0 AS CityId, -- Id AS 
				0 AS StateId,
				0 AS City, -- Title AS 
				0 AS CreatedUserId,
				0 AS CreatedDateTime,
				0 AS IsObsolete				
		-- FROM sCommon.tCityMaster
		 --WHERE OrgId = 	@rOrgId --Commented as No orgid is there in table
			--ORDER BY CityId
			--WHERE IsObsolete = 0		
			
--SET @lResult = 1
END
GO
PRINT N'Altering Procedure [sSecurity].[pDashletGet]...';


GO
ALTER PROCEDURE [sSecurity].[pDashletGet]
	@rOrgGroupId int=0,
	@rDate date='',
	@rDashletId int=0,
	@rOrgGroupBatchId int=0,
	@rUserId bigint=0,
	@rUserSourceId bigint=0,
	@rUserSourceTypeId int=0,
	@rOrgId Int=0,
	@rSourceTypeId smallint=0,
	@rSourceId bigint=0,
	@rBatchId int=0,
	@rExamId int=0,
	@rStatusId int =0


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
	DECLARE @TimeZoneDate datetime
	SET  @TimeZoneDate=sCommon.fGetDate()
	if(@rDashletId='1')
	BEGIN
		exec sCommunication.pCircularListGet @rUserSourceId=@rUserSourceId,@rOrgGroupBatchId=@rOrgGroupBatchId,@rUserSourceTypeId=@rUserSourceTypeId,@rUserId=@rUserId,@rStartDate=@rDate
	END
	if(@rDashletId='2')
	BEGIN
		SELECT  N.Id,N.Title FROM sCommunication.tNews N WHERE N.OrgGroupBatchId=@rOrgGroupBatchId AND Convert(date,N.CreatedDateTime)=convert(date,@TimeZoneDate)
	END
	if(@rDashletId='3')
	BEGIN
		exec sActivity.pMyEventGet @rSourceTypeId=@rSourceTypeId,@rSourceId=@rSourceId,@rOrgId=@rOrgId,@rBatchId=@rBatchId,@rFromDate=@rDate,@rToDate=@rDate
	END
	if(@rDashletId='4')
	BEGIN
		exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=1,@rStatus=0,@rIsSearch=1
	END
	if(@rDashletId='5')
	BEGIN
		exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=0,@rStatus=0,@rIsSearch=1
	END
	if(@rDashletId='6')
	BEGIN
		DECLARE @BirthdayDays int=0
		IF EXISTS (SELECT 1 FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 355 AND SourceTypeId = 1016 AND SourceId = @rOrgId)
		BEGIN
			SET @BirthdayDays = (SELECT ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 355 AND SourceTypeId = 1016 AND SourceId = @rOrgId)
		END
		ELSE
		BEGIN
			SET @BirthdayDays = 7
		END
		SELECT EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName AS Name, EM.DepartmentName, EM.DateOfBirth AS DateOfBirth
		FROM [sHrm].[vExtEmployeeMaster] EM
		WHERE EM.OrgId = @rOrgId
		--AND (MONTH(EM.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND EM.DateOfBirth!='' AND EM.StatusId=7
		--AND (DAY(EM.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))
		--AND(MONTH(EM.DateOfBirth) <= CAST(MONTH(@TimeZoneDate) AS varchar(2)) AND MONTH(EM.DateOfBirth) >= CAST(MONTH(@TimeZoneDate) AS varchar(2)))
		--AND(DAY(EM.DateOfBirth) <= CAST(DAY(@TimeZoneDate+@BirthdayDay) AS varchar(2)) AND DAY(EM.DateOfBirth) >= CAST(DAY(@TimeZoneDate) AS varchar(2)))

			AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) <= CONVERT(VARCHAR(5),@TimeZoneDate+@BirthdayDays,110)
			AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) >= CONVERT(VARCHAR(5),@TimeZoneDate,110)
			AND EM.DateOfBirth!='' AND EM.StatusId=7
		ORDER BY CONVERT(VARCHAR(5),EM.DateOfBirth,110)
	END
	if(@rDashletId='7')
	BEGIN
		SELECT SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name, SC.ClassName+' '+SC.DivisionName AS ClassName FROM sStudent.vStudentAllDetail SC
		WHERE SC.OrgId=@rOrgId AND SC.BatchId=@rBatchId
			AND (MONTH(SC.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND SC.DateOfBirth!='' AND SC.StatusId=1
			AND (DAY(SC.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))
	END
	if(@rDashletId='10')
	BEGIN
		exec sAttendance.pDashletAttendanceStatusGet @rAcademicId=@rSourceId
	END

	if(@rDashletId='11')
	BEGIN
		SELECT EM.EmployeeName,L.FromDate,L.ToDate
		FROM  sHrm.tLeave L
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
		WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND L.OrgId = @rOrgId
			AND (EJD.EmployeeManagerId = @rUserSourceId OR @rUserSourceId = 0)
			--AND ((L.FromDate >= @rDate) OR (ISNULL(@rDate,'') = '')) --comment for Mantis Id: 0030464
			AND EM.EmployeeStatusId=7
			AND L.StatusId = 549
		--exec [sHrm].[pLeaveListingGet] @rOrgId=@rOrgId,@rEmployeeId=@rUserSourceId,@rLeaveTypeId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromDate=@rDate,@rTodate=''
	END
	if(@rDashletId='12')
	BEGIN
		exec sCommunication.pPollGet @rOrgGroupBatchId=@rOrgGroupBatchId,@rSourceTypeId=@rUserSourceTypeId,@rCreatedUserId=@rUserId,@rCreatedDateTime=@rDate
	END
	if(@rDashletId='14')
	BEGIN
		exec sCommunication.pMyBookGet @rReaderSourceTypeId=@rUserSourceTypeId,@rReaderSourceId=@rUserSourceId,@rBatchId=@rBatchId,@rStatusId=@rStatusId
	END
	if(@rDashletId='16')
	BEGIN
		exec [sFee].[pRptFeeReceiptTotalGet] @rFromDate=@rDate,@rToDate=@rDate,@rOrgGroupBatchId=@rOrgGroupBatchId
	END

	if(@rDashletId='17')
	BEGIN
		exec [sFee].[pFeeDueAlertGet] @rSourceId=@rSourceId,@rSourceTypeId=@rSourceTypeId,@rBatchId=@rBatchId
	END
	if(@rDashletId='18')
	BEGIN
		exec sCommunication.pBlogGet @rId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rTitle=NULL,@rCreatedUserId=0,@rOrgId=@rOrgId,@rCreatedDateTime=@rDate
	END
	if(@rDashletId='19')
	BEGIN
		exec sAssessment.pStudentResultGet @rAcademicId=@rSourceId,@rStudentId=@rUserSourceId,@rBatchId=@rBatchId,@rExamId=@rExamId
	END
	if(@rDashletId='21')
	BEGIN
		SELECT vCD.ClassDivisionName,ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName, CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rDate,1,0)) =0 THEN 'Pending' ELSE 'Complete' END ELSE 'Complete' END AS PresentStatus
		FROM sStudent.tAcademic A
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId  AND A.BatchId=@rBatchId AND vCD.IsObsolete=0
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
			LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceTypeId = 1 AND SR.IsPresent=1 AND SR.AttendanceDate=@rDate
		GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName
		ORDER BY vCD.OrderIndex
	END
	if(@rDashletId='22')
	BEGIN
		SELECT VL.Id,VL.VisitorName, VL.NoOfVisitor,  (isnull(case when isnull(VL.WhomToMeet,0)!=0 then isnull(EM.EmployeeName,'') else ISNULL(VL.WhomToMeetName,'') end,'' )) AS WhomToMeetName
		FROM sFrontOffice.tVisitorLog VL
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=VL.WhomToMeet
		WHERE VL.OrgId=@rOrgId AND VL.VisitDate=@rDate
		ORDER BY VL.VisitDate DESC,VL.InTime DESC
	END
	if(@rDashletId='23')
	BEGIN
		SELECT DispatchedTo, DispatchedCity  FROM sFrontOffice.tCourierDispatch  WHERE OrgGroupId=@rOrgGroupId AND DispatchDate=@rDate  AND @rDashletId='23' ORDER BY DispatchDate
	END
	if(@rDashletId='24')
	BEGIN
		SELECT ReceiveFrom, ReceiveFor  FROM  sFrontOffice.tCourierReceive  WHERE OrgGroupId=@rOrgGroupId  AND ReceiveDate=@rDate  AND @rDashletId='24' ORDER BY ReceiveDate
	END
	if(@rDashletId='25')
	BEGIN
		SELECT ISNULL(Ps.LectureNumber,'') AS LactureNumber,PS.EmployeeId,ISNULL(SMT.Title,'') AS Subject,ISNULL(EM1.FirstName,'') + ' '+ISNULL(EM1.LastName,'') AS EmployeeName,ISNULL(Em.FirstName,'') + ' '+ISNULL(Em.LastName,'') AS ProxyEmployeeName, ISNULL(DV
.Code,'') AS ClassDivisionName,ISNULL(SM.Title,'') AS ProxySubject
		from sTimetable.tProxySetting PS
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = PS.DayId
			INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = PS.DivisionId
			INNER JOIN sTimetable.tTimeTable TT ON TT.Id=PS.TimeTableId
			INNER JOIN sSetup.tSubjectMaster SMT ON SMT.Id = TT.SubjectId
			INNER JOIN sHrm.tEmployeeMaster EM1  ON TT.EmployeeId=EM1.Id
			INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = PS.EmployeeId
		WHERE PS.ProxyDate=@rDate AND PS.BatchId=@rBatchId AND ((PS.EmployeeId=@rSourceId) OR (@rSourceId=0))
		ORDER BY PS.ProxyDate
	END

	if(@rDashletId='27')
	BEGIN
		--Asset Check
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),AM.CheckedLastDate,103) AS CheckedLastDate
		FROM sAssetManagement.tAssetMaster AM
			INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId
			INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		WHERE ISNULL(AM.IsCheckRequired,0) = 1 AND (AM.CheckFrequencyId=1 AND AM.CheckedLastDate <=  DATEADD(dd,1,@TimeZoneDate) OR AM.CheckFrequencyId=2 AND AM.CheckedLastDate <=  DATEADD(dd,7,@TimeZoneDate) OR AM.CheckFrequencyId=3 AND AM.CheckedLastDate <= DATEADD(dd,30,@TimeZoneDate)) AND AU.InchargeUserId =   @rUserId AND AM.OrgGroupId = @rOrgGroupId



		--SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
		--AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate
		--FROM sAssetManagement.tAssetMaster AM
		--INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId
		--INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		-- WHERE AU.InchargeUserId = @rUserId AND AM.OrgGroupId = @rOrgGroupId
	END
	if(@rDashletId='28')
	BEGIN
		--Asset maintenance
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate
		FROM sAssetManagement.tAssetMaster AM
			INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId
			INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		WHERE AU.InchargeUserId = @rUserId AND AM.OrgGroupId = @rOrgGroupId
	END
	if(@rDashletId='29')
	BEGIN
		--Asset Renew
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),AM.RenewLastDate,103) AS RenewLastDate, CONVERT(nvarchar(12),AM.RenewNextDate,103) AS RenewNextDate
		FROM sAssetManagement.tAssetMaster AM
			INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId
			INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		WHERE ISNULL(AM.IsRenewRequired,0) = 1
			--AND AM.RenewNextDate >= DATEADD(dd,ISNULL(AM.RenewAlertBeforeDays,0),AM.RenewLastDate)
			AND convert(Date,@TimeZoneDate) >=  DATEADD(dd,-ISNULL(AM.RenewAlertBeforeDays,0), AM.RenewNextDate)
			AND AU.InchargeUserId =  @rUserId
			AND AM.OrgGroupId = @rOrgGroupId
	END
	--Inward
	IF(@rDashletId='30')
	BEGIN
		DECLARE @InwardRegisterGrid VARCHAR(max)=''
		SELECT  @InwardRegisterGrid = @InwardRegisterGrid + '<tr>
	       <td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterFrom,'') + '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(ReceivedDate,'01/01/0001'),103) + '</td>
	 	</tr>'
		FROM sFrontOffice.tInwardRegister
		WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId AND ReceivedDate<=convert(Date,@TimeZoneDate)
		Order by ReceivedDate Desc

		SELECT Isnull(@InwardRegisterGrid,'') As InwardRegisterGrid
	END
	--Outward
	IF(@rDashletId='31')
	BEGIN
		DECLARE @OutwardRegisterGrid VARCHAR(max)=''
		SELECT  @OutwardRegisterGrid = @OutwardRegisterGrid + '<tr>
			<td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
			<td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
			<td align="left" scope="col">' + ISNULL(LetterTo,'') + '</td>
			<td align="left" scope="col">' + convert(varchar,isnull(OutWardDate,'01/01/0001'),103) + '</td>
	 	</tr>'
		FROM sFrontOffice.tOutwardRegister
		WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId AND OutwardDate<=convert(Date,@TimeZoneDate)
		Order by OutwardDate Desc

		SELECT Isnull(@OutwardRegisterGrid,'') As	OutwardRegisterGrid
	END

	IF(@rDashletId='32')
	BEGIN
		DECLARE @ReorderQuantityGrid VARCHAR(max)=''
		SELECT   @ReorderQuantityGrid=@ReorderQuantityGrid+'<tr>
			<td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
			<td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
			<td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
			<td align="left" scope="col">' + convert(varchar,isnull(SP.ReOrderQuantity,0)) + '</td>
		</tr>'
		FROM sProcurement.tStockBatch SB
			INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
			INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
			INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
			--INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
		WHERE SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0
		group by SE.Title,SM.Title,SP.ReOrderQuantity,SP.ReOrderPoint
		HAVING SUM(SB.AvailableQuantity) < SP.ReOrderPoint

		SELECT Isnull(@ReorderQuantityGrid,'') As	ReorderQuantityGrid
	END

	IF(@rDashletId='33')
	BEGIN
		DECLARE @SafetyStockGrid VARCHAR(max)=''
		SELECT   @SafetyStockGrid=@SafetyStockGrid+'<tr>
			<td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
			<td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
			<td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
			<td align="left" scope="col">' + convert(varchar,isnull(SP.SafetyStock,0)) + '</td>
		</tr>'
		FROM sProcurement.tStockBatch SB
			INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
			INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
			INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
			--INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
		WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0
		group by SE.Title,SM.Title,SP.SafetyStock,SP.ReOrderPoint
		HAVING SUM(SB.AvailableQuantity) < SP.SafetyStock

		SELECT Isnull(@SafetyStockGrid,'') As	SafetyStockGrid
	END
	IF(@rDashletId='34')
	BEGIN
		DECLARE @Increment varchar(max)=''
		SELECT @Increment=@Increment+'<tr>
			<td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
			<td align="left" scope="col">' +convert(varchar,isnull(IncrementDate,'01/01/0001'),103)  + '</td>
		</tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE IncrementDate BETWEEN GETDATE()-1 AND GETDATE()+7 AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Increment, '') As IncrementGrid
	END

	IF(@rDashletId='78')
	BEGIN
		DECLARE @Retirement varchar(max)=''
		SELECT @Retirement=@Retirement+'<tr>
			<td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
			<td align="left" scope="col">' +convert(varchar,isnull(RetirementDate,'01/01/0001'),103)  + '</td>
		</tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE RetirementDate BETWEEN GETDATE()-1 AND GETDATE()+30 AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Retirement, '') As RetirementGrid
	END

	if(@rDashletId='83')
	BEGIN
		SELECT SA.Name,L.LeaveFromDate,L.LeaveToDate
		FROM sAttendance.tStudentLeaveRequest L
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		WHERE SA.BatchId = @rBatchId
			AND SA.OrgId = @rOrgId
			--Comment for Mantis Id:0029925
			--AND ((L.LeaveFromDate <= @rDate) OR (ISNULL(@rDate,'') = ''))
			--AND ((L.LeaveToDate >= @rDate) OR (ISNULL(@rDate,'') = ''))
			AND SA.StatusId=1
			AND L.StatusId IS NULL
	END

	IF(@rDashletId='85')
	BEGIN
		SELECT
			AF.Id,
			AF.AdmissionInquiryId,
			ISNULL(AF.FollowupDate,'') AS  FollowupDate,
			AF.FollowupRemark,
			AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name,
			AI.Number AS InquiryNumber
		FROM
			sAdmission.tAdmissionInquiryFollowup AF
			INNER JOIN sAdmission.tAdmissionInquiry AI ON AI.Id=AF.AdmissionInquiryId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
		WHERE ((AF.FollowupDate < @rDate) OR (ISNULL(@rDate,'')=''))
			AND ((AI.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		Order by AF.FollowupDate DESC
	END

	IF(@rDashletId='86')
	BEGIN
		SELECT
			AF.Id,
			AF.AdmissionInquiryId,
			ISNULL(AF.FollowupDate,'') AS  FollowupDate,
			AF.FollowupRemark,
			AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name,
			AI.Number AS InquiryNumber
		FROM
			sAdmission.tAdmissionInquiryFollowup AF
			INNER JOIN sAdmission.tAdmissionInquiry AI ON AI.Id=AF.AdmissionInquiryId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
		WHERE ((AF.FollowupDate = @rDate) OR (ISNULL(@rDate,'')=''))
			AND ((AI.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		Order by AF.FollowupDate DESC
	END

	IF(@rDashletId='87')
	BEGIN
		Declare @lOrgGroupBatchId int=0
		select @lOrgGroupBatchId=OrgGroupBatchId from sSetup.tBatchMaster where Id=@rBatchId
		SELECT Distinct
			PDP.Id
			,ISNULL(SA.Code, '') AS IdNo
			,ISNULL(SA.Name, '') AS StudentName
			,PDP.Amount AS ReceiptAmount
			,PDP.ChequeNo
			,PDP.PaymentClearanceDate
		FROM
			sFee.tPostDatePayment PDP
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = PDP.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = PDP.BatchId
			INNER JOIN [sStudent].[vStudentAcademic] SA ON SA.AcademicId = PDP.SourceId AND PDP.SourceTypeId = 2001
		--Mantis: 40861, comment the below where condition and add new where condition
		--WHERE  (PDP.OrgId = @rOrgId OR @rOrgId = 0)
		--	AND (PDP.BatchId = @rBatchId OR @rBatchId = 0)
		--	AND (PDP.PaymentClearanceDate <= @rDate OR ISNULL(@rDate, '') = '')
		--	AND PDP.StatusId = 751
		WHERE (PDP.OrgGroupBatchId = @lOrgGroupBatchId OR @lOrgGroupBatchId = 0)
			AND (PDP.PaymentClearanceDate <= @rDate OR ISNULL(@rDate, '') = '')
			AND PDP.StatusId = 751
		ORDER BY PDP.PaymentClearanceDate DESC
	END

--Added by dhananjay for mantis : 41224
	IF(@rDashletId='88')
	BEGIN
		DECLARE @lForDate nvarchar(20), @Query nvarchar(max)
 
		Set @lForDate = Right('0'+(convert(nvarchar(2),(Day(@rDate)))),2)
 
		SET @Query='SELECT EM.Id as EmployeeId,  ISNULL(EM.FirstName, '''') + '' '' + ISNULL(EM.LastName, '''') AS EmpName, 
			isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ '+@lForDate+') as datetime),
			cast(rtrim(YEAR('''+convert(nvarchar(max),@rDate)+''') *10000+ Month('''+convert(nvarchar(max),@rDate)+''') *100+ '+@lForDate+') as datetime)),
			D'+@lForDate+',ISNULL(D'+@lForDate+'_IN,''00:00'') as FirstIn,ISNULL(D'+@lForDate+'_OUT,''00:00'') as LastOut,
			D'+@lForDate+'_O,D'+@lForDate+'_L,D'+@lForDate+'_T,D'+@lForDate+'_E,D'+@lForDate+'_S 
			FROM sHRM.tEmployeeMaster EM
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
				LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId 
						AND MT.ATTN_DT = cast(rtrim(YEAR('''+convert(nvarchar(max),@rDate)+''') *10000+ Month('''+convert(nvarchar(max),@rDate)+''') *100+ 01) as datetime)
			WHERE (EM.Id = '+convert(nvarchar(max),@rSourceId)+' OR '+convert(nvarchar(max),@rSourceId)+' = 0)
			AND EM.OrgId = '+convert(nvarchar(max),@rOrgId)+'
			AND (EJD.DateOfJoining<= '''+convert(nvarchar(max),@rDate)+''')
			AND (EJD.DateOfleaving>= '''+convert(nvarchar(max),@rDate)+''' OR ISNULL(EJD.DateOfleaving,'''')='''')
			AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
			AND EM.StatusId=7'
 
		EXEC(@Query)
	END
	--Added by dhananjay for mantis : 41224
END
GO
PRINT N'Altering Procedure [sSecurity].[pUserLocationListGet]...';


GO
ALTER   PROCEDURE [sSecurity].[pUserLocationListGet]
          
           @rOrgId int,
           @rUserId bigint
      
 
AS
SET NOCOUNT ON

BEGIN
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
--SELECT ISNULL(UL.UserId,0) AS UserId     
--      ,SLM.Id AS StorLocationId      
--      ,SLM.Title AS StoreLocation
--      ,LM.Title As Location
--      ,(CASE WHEN UL.UserId IS NULL THEN 'False' 
--       ELSE 'True' END) AS Selected   
--FROM sIp.tStoreLocationMaster  SLM
--	  LEFT JOIN  sCommon.tLocationMaster LM ON  SLM.LocationId =  LM.Id  
--	  LEFT JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id 
--	  AND UL.UserId = @rUserId
     
--      WHERE SLM.OrgId = @rOrgId AND   SLM.IsObsolete = 0
	
      SELECT 0 AS UserId     
      ,0 AS StorLocationId      
      ,0 AS StoreLocation
      ,0 As Location
      ,0 AS Selected   
		
END
GO
PRINT N'Altering Procedure [sSecurity].[pUserWithEmployeeDetailByEmployeeId_Delete]...';


GO
ALTER   PROCEDURE [sSecurity].[pUserWithEmployeeDetailByEmployeeId_Delete]
	@rEmployeeId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'PermanentAddressId'., Invalid column name 'CommunicationAddressId'.
	--SELECT 
	--	E.UserId AS UserId,		
	--	UserIsObsolete AS UserIsObsolete,
	--	DisplayTitle AS DisplayTitle,
	--	LoginTitle AS LoginTitle,
	--	EmployeeId AS EmployeeId, 
	--	EmployeeCode AS EmployeeCode,
	--	FullName AS EmployeeFullName,
	--	FirstName AS FirstName,
	--	MiddleName AS MiddleName,
	--	LastName AS LastName,
	--	EmployeeTypeId AS EmployeeTypeId,
	--	EmployeeCategoryId AS EmployeeCategoryId,
	--	GenderId AS GenderId,
	--	DateOfBirth AS DateOfBirth,
	--	DateOfJoining AS DateOfJoining,
	--	--PermanentAddressId AS PermanentAddressId,
	--	0 AS PermanentAddressId,
	--	0 AS CommunicationAddressId,
	--	--CommunicationAddressId AS CommunicationAddressId,
	--	--CommunicationContactId AS CommunicationContactId,
	--	--EC.PhoneNumber AS PhoneNumberHome,
	--	--E.PhoneNoCompany AS PhoneNumberOffice,
	--	--EC.MobileNumber AS PhoneNumberMobile,
	--	E.CompanyEmail AS EmailPrimary,
	--	--EC.Email AS EmailAlternative,
	--	E.OrganizationDepartmentId AS OrganizationDepartmentId,
	--	E.OrganizationDepartment AS OrganizationDepartment,
	--	UP.ElectronicSignature AS ElectronicSignature
		
	--FROM 
	--	sCommon.vExtEmployeeWithAllUser E
	--	--LEFT JOIN sHrm.vExtEmployeeContact EC	
	--	--		ON E.CommunicationContactId = EC.Id
				
	--	LEFT JOIN sSecurity.tUserProfile UP
	--			ON UP.UserId = E.UserId
	--WHERE
	--	EmployeeId = @rEmployeeId
	SELECT 
		0 AS UserId,		
		0 AS UserIsObsolete,
		0 AS DisplayTitle,
		0 AS LoginTitle,
		0 AS EmployeeId, 
		0 AS EmployeeCode,
		0 AS EmployeeFullName,
		0 AS FirstName,
		0 AS MiddleName,
		0 AS LastName,
		0 AS EmployeeTypeId,
		0 AS EmployeeCategoryId,
		0 AS GenderId,
		0 AS DateOfBirth,
		0 AS DateOfJoining,
		0 AS PermanentAddressId,
		0 AS CommunicationAddressId,
		0 AS EmailPrimary,
		0 AS OrganizationDepartmentId,
		0 AS OrganizationDepartment,
		0 AS ElectronicSignature
		
END
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentRegisterWithSUIDAndDemographicDetailGet]...';


GO


ALTER PROCEDURE [sStudent].[pRptStudentRegisterWithSUIDAndDemographicDetailGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rClassStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 --@rFromAdmissionDate date='', 
  --   @rToAdmissionDate date='',
     @rFromStudentCode nvarchar(max)='',
     @rToStudentCode nvarchar(max)='',
	 @rFromNumber int = 0,
	 @rToNumber int = 0  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN

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

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


	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SD.AcademicId,
			SD.OrgId ,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassDivision,
			SD.Code,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,		
			SD.ClassName,
			SD.ClassId ,
			SD.DivisionId,
			SD.DivisionName,
			SD.StatusName,
			SD.StatusId,
			SD.LCProgress,
			SD.Religion,
			SD.FamilyCast,
			SD.FamilySubCast,
			SD.LCConduct,
			SD.BirthPlace,
			SD.BirthTaluka,
			SD.BirthDistrict,
			SD.LeftDate,
			SD.PreviousSchool,
			SD.DateOfBirth,
			SD.BirthDateInWord,
			SD.LeftReason,
			SD.AdmissionDate,
			SD.AdmissionStandard,
			SD.LeftStandard,
			SD.LCNumber,
			SD.LCDate,
			SD.StudentPhoto,
			SD.BloodGroup,
			SD.PresentAddress,
			SD.ContactNo,
			SD.Batch,
			SD.BatchId,
			SD.InactiveDate,
			OM.Title AS OrgName,
			SF.MotherName,
			SD.DivisionOrder,
			SD.Number AS StudentNumber,
			SF.FatherName,
			SD.Nationality,
			SD.MotherTongue,
			SD.BirthState,
			SD.BirthCountry,
			SD.SUId,
            SD.AdhaarNumber,
            SD.ClassStatusId,
            SD.ClassStatusName,
			SD.UIDNumber ,
			SD.Gender ,
			HM.Title As HouseName ,
			SO.ReferenceRemark as ReferenceRemark ,
			TM.Title as TribeTitle,
			ISNULL(STUFF((
			SELECT ', ' +  ISNULL(CTM.Title,'')
			FROM [sStudent].[tStudentCustomTag] CT 
			INNER JOIN [sStudent].[tCustomTagMaster] CTM ON CT.CustomTagId=CTM.Id 
			WHERE CT.StudentId = SD.StudentId
			FOR XML PATH('')
			), 1, 1, ''),'') AS CustomTags ,
			CCM.Title As CasteCategory ,
		    @lIDConfigValue AS ItemValue,
			SM.ApaarIdNumber	--Mantis - 45134			
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassID AND BC.BatchId = SD.BatchId AND SD.BatchId= @rBatchId
			--LEFT JOIN sStudent.tStudentAdmission SAM ON SD.StudentId=SAM.StudentId
			--AND ((SAM.AdmissionDate>=@rFromAdmissionDate)OR(ISNULL(@rFromAdmissionDate,'')=''))    
			--AND ((SAM.AdmissionDate<=@rToAdmissionDate)OR(ISNULL(@rToAdmissionDate,'')=''))  
			--AND	SAM.BatchId = @rBatchId 
			LEFT JOIN sActivity.tHouseMaster HM ON HM.ID = SD.HouseId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SD.StudentId
			LEFT JOIN sCommon.tTribeMaster TM ON TM.ID = SO.TribeId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SD.CastCategoryId
			LEFT JOIN sStudent.tStudentMaster SM On SM.Id = SD.StudentID

			 
	WHERE 
			SD.OrgId=@rOrgId
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SD.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND ((MONTH(SD.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=0))
	    AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	    AND((SD.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	    AND((SD.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))
		AND((SD.Number>=@rFromNumber) OR (ISNULL(@rFromNumber,0)=0))
	    AND((SD.Number<=@rToNumber) OR (ISNULL(@rToNumber,0)=0))
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentDataModify]...';


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

DECLARE @loDoc INT

--BEGIN TRY
--BEGIN TRANSACTION

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

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup' 
			 OR @rSubCategoryField = 'TransportMode' OR @rSubCategoryField = 'House'
			OR @rSubCategoryField = 'Quota' 
			OR @rSubCategoryField = 'Nationality' OR @rSubCategoryField = 'AdmissionStandard' OR  @rSubCategoryField = 'AdmissionCategory' 
			OR @rSubCategoryField = 'AdmissionQuota'
			OR @rSubCategoryField = 'Tribe')
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	
	IF(	@rSubCategoryField = 'CasteCategory' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast') + 'Id'
	END
	
	IF(	@rSubCategoryField = 'FamilyCaste' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')  
	END
	
	IF(	@rSubCategoryField = 'StudentGroup' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'StudentGroup','StudentGroupId')  
	END
	IF(	@rSubCategoryField = 'StudentOtherGroup' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'StudentOtherGroup','StudentOtherGroupId')  
	END
	
	IF(@rSubCategoryField = 'FeeCategory' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'FeeCategory','AdmissionCategory') + 'Id'
	END

	IF(@rSubCategoryField = 'FatherAnnualIncome' )													-- #Start Mantis Id : 0029214
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'FatherAnnualIncome','FatherIncome')
	END
	IF(@rSubCategoryField = 'MotherAnnualIncome' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'MotherAnnualIncome','MotherIncome')
	END																								
	IF(@rSubCategoryField = 'RelativeAnnualIncome' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'RelativeAnnualIncome','RelativeIncome')
	END																								-- #End Mantis Id : 0029214

	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(200),UpdatedUserId bigint,IsExist bit); --SubCategory 150 to 200 - 0044848
	
	IF(@rCategoryId= 1)  
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication) 
		
		set @sql='INSERT INTO sStudent.tStudentCommunication 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentCommunication set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentCommunication SC 
					INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentOther) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
			set @sql='INSERT INTO sStudent.tStudentOther 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sStudent.tStudentOther SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			set @sql='INSERT INTO sStudent.tStudentOther 
						(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
						SELECT
							LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
						FROM
							ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	    
	Else IF(@rCategoryId= 3)
		BEGIN	
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(200), --mantis : 0044848 100 to 200
						UpdatedUserId bigint)	
						)E 	

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

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

		IF(@rSubCategoryField = 'RelativeDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE RelativeDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END		

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

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

			IF(@rSubCategoryField IN ('AdmissionCategoryId'))
			BEGIN
				set @sql='UPDATE sStudent.tStudentMaster set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentMaster SM
						INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
						INNER JOIN ListofData LD ON A.Id=LD.Id AND IsExist=0'
		
				Exec sp_executesql @sql
			END
			Drop Table ListofData
		
		END
		
			 SELECT 1 AS StatusCode
	    END			 
	 
	 
	 Else IF(@rCategoryId= 8)
	     BEGIN
	     
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 

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


GO
ALTER PROCEDURE [sStudent].[pStudentImportExamWiseGet]
	@rClassId int=0,
	@rDivisionId int=0,
	@rOrgId int,
	@rBatchId int,
	@rExamId int,
	@rStatus int=0,
	@rIsDisplayPendingAmount bit = 0		-- Mantis Id : 0044572
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 
	
	--Changes for Mantis Id : 0031796   
	SELECT AR2.Id,AR2.ParticipantSourceId,AR2.ParticipantSourceTypeId,AR2.WorkflowFunctionalityId INTO #Temp_ExamApprovalRequest 
	FROM (Select AR.ParticipantSourceId,
	(SELECT TOP 1 AR1.CreatedDateTime FROM sWorkflow.tApprovalRequest AR1 
	WHERE AR.ParticipantSourceId = AR1.ParticipantSourceId AND AR1.WorkflowFunctionalityId = 1
	ORDER BY AR1.CreatedDateTime DESC) AS CreatedDateTime
	from sWorkflow.tApprovalRequest AR GROUP BY AR.ParticipantSourceId) AR1
	INNER JOIN  sWorkflow.tApprovalRequest AR2 ON AR1.CreatedDateTime = AR2.CreatedDateTime AND AR1.ParticipantSourceId = AR2.ParticipantSourceId
	LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR2.Id
	LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		
	SELECT 
		SA.Id AS AcademicId,
		SA.StudentId,
		ISNULL(SA.RollNo,0) AS RollNo,
		SM.FirstName+' '+SM.LastName AS Name,
		SM.Code,
		STM.Id AS StatusId,
		STM.Title AS StatusName,		
		CM.Id AS ClassId,
		CM.Title AS ClassName,
		DM.Id AS DivisionId,
		DM.Title AS DivisionName,
		 R.Percentage,
		ISNULL(SA.ExemptionTypeId,0) AS ExemptionTypeId,
		ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId ,
		--CASE WHEN ASM.Title IS NULL THEN 'NA' ELSE ASM.Title END AS LCStatus,
		CASE WHEN AR.WorkflowFunctionalityId = 1 THEN (
		CASE WHEN (ASM.Title IS NULL  AND AR.WorkflowFunctionalityId IS NULL)THEN 'NA' 
		WHEN  (ASM.Title IS NULL  AND AR.WorkflowFunctionalityId IS NOT NULL) THEN 'Pending'
		ELSE ASM.Title END)	ELSE 'NA' END AS LCStatus,
		R.ResultStatus,
		ISNULL(SM.SUId,'') as SUId,			-- Mantis : 0041176 For : SM.SUId
		CASE WHEN @rIsDisplayPendingAmount = 1 
			THEN ISNULL(sFee.fPendingFeeAmountAcademicIdwiseGet(SA.ID),0)
			ELSE 0.00 END AS PendingAmount		-- Mantis Id : 	0044572
			
    FROM 
           sStudent.tAcademic SA
           INNER JOIN sStudent.tStudentMaster SM
           ON SM.Id=SA.StudentId
           INNER JOIN sStudent.tStatusMaster STM
           ON STM.Id=SM.StatusId
           INNER JOIN sSetup.tClassMaster CM
           ON CM.Id=SA.ClassId
           INNER JOIN sSetup.tDivisionMaster DM
           ON DM.Id=SA.DivisionId             
           INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
           INNER JOIN sAssessment.tResult R ON R.AcademicId= SA.Id AND R.ExamId = EM.Id
		   LEFT JOIN #Temp_ExamApprovalRequest AR ON AR.ParticipantSourceId = SA.Id AND AR.ParticipantSourceTypeId = 2001
		   LEFT JOIN sWorkflow.tApprovalAction AA 
		   ON AA.ApprovalRequestId = AR.Id
		   LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
	WHERE  
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND(SA.OrgId=@rOrgId)
		AND  (R.ExamId =@rExamId)
		AND ((STM.Id=@rStatus) OR (@rStatus=0))		
	ORDER BY R.Percentage desc, SA.RollNo		
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentImportGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentImportGet]
	@rClassId int=0,
	@rDivisionId int=0,
	@rOrgId int,
	@rBatchId int,
	@rStatusId int=0,
	@rCode nvarchar(20)='',
	@rIsDisplayPendingAmount bit = 0		-- Mantis Id : 0044572
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	--Changes for Mantis Id : 0031796   
	SELECT AR2.Id,AR2.ParticipantSourceId,AR2.ParticipantSourceTypeId,AR2.WorkflowFunctionalityId 
	INTO #Temp_ApprovalRequest
	FROM (Select AR.ParticipantSourceId,
	(SELECT TOP 1 AR1.CreatedDateTime FROM sWorkflow.tApprovalRequest AR1 
	WHERE AR.ParticipantSourceId = AR1.ParticipantSourceId AND AR1.WorkflowFunctionalityId = 1
	ORDER BY AR1.CreatedDateTime DESC) AS CreatedDateTime
	from sWorkflow.tApprovalRequest AR GROUP BY AR.ParticipantSourceId) AR1
	INNER JOIN  sWorkflow.tApprovalRequest AR2 ON AR1.CreatedDateTime = AR2.CreatedDateTime AND AR1.ParticipantSourceId = AR2.ParticipantSourceId
	LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR2.Id
	LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		
	SELECT 
		SA.Id AS AcademicId,
		SA.StudentId,
		ISNULL(SA.RollNo,0) AS RollNo,
		--SM.FirstName+' '+SM.LastName AS Name, --Commented for mantis : 35346 by Nilesh    
		sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName, OM.StudentNameFormatId) AS Name,--Added for mantis : 35346 by Nilesh    
		SM.Code,
		STM.Id AS StatusId,
		STM.Title AS StatusName,		
		CM.Id AS ClassId,
		CM.Title AS ClassName,
		DM.Id AS DivisionId,
		DM.Title AS DivisionName,
		ISNULL(SA.ExemptionTypeId,0) AS ExemptionTypeId,
		ISNULL(SA.FeeStructureId,0) AS FeeStructureId,
		ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
		CASE WHEN AR.WorkflowFunctionalityId = 1 THEN (
		CASE WHEN (ASM.Title IS NULL  AND AR.WorkflowFunctionalityId IS NULL)THEN 'NA' 
		WHEN  (ASM.Title IS NULL  AND AR.WorkflowFunctionalityId IS NOT NULL) THEN 'Pending'
		ELSE ASM.Title END)ELSE 'NA' END AS LCStatus,
		ISNULL(SM.SUId,'') as SUId,			 -- Mantis : 0041176 For : SM.SUId
		CASE WHEN @rIsDisplayPendingAmount = 1 
			THEN ISNULL(sFee.fPendingFeeAmountAcademicIdwiseGet(SA.ID),0)
			ELSE 0.00 END AS PendingAmount		-- Mantis Id : 	0044572
    FROM 
           sStudent.tAcademic SA
           INNER JOIN sStudent.tStudentMaster SM
           ON SM.Id=SA.StudentId
           INNER JOIN sStudent.tStatusMaster STM
           ON STM.Id=SM.StatusId
           INNER JOIN sSetup.tClassMaster CM
           ON CM.Id=SA.ClassId
           INNER JOIN sSetup.tDivisionMaster DM
           ON DM.Id=SA.DivisionId  
		   LEFT JOIN #Temp_ApprovalRequest AR ON AR.ParticipantSourceId = SA.Id AND AR.ParticipantSourceTypeId = 2001
		   LEFT JOIN sWorkflow.tApprovalAction AA 
		   ON AA.ApprovalRequestId = AR.Id
		   LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		   INNER JOIN sSetup.tOrganizationMaster AS OM ON SA.OrgId = OM.Id--Added for mantis : 35346 by Nilesh                 
	WHERE  
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND(SA.OrgId=@rOrgId)
		AND ((STM.Id=@rStatusId) OR (@rStatusId=0))
		AND (SM.Code=@rCode OR ISNULL(@rCode,'')='')
	ORDER BY SA.RollNo		
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentVerificationUpdate]...';


GO

 
 
ALTER PROCEDURE [sStudent].[pStudentVerificationUpdate]
	 
	@rAdmissionDate date='',
	@rPreviousSchool nvarchar(200)='', --nvarchar(50) to nvarchar(200) mantis : 0044848
	@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,
	@rBirthdateInWord nvarchar(150) = '' --mantisid - 0033546
	
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,BirthDateInWord = @rBirthdateInWord Where StudentId=@rStudentId
		END
		--ADD BirthDateInWord in Update due to matisid - 0033546
		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 [sTimetable].[pRptDivisionTimeTableGet]...';


GO


ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

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

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

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	0 As IsPresent,
	'' As WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	'' as DivisionIncharge,
	IsBreak,
	IsBreakBefore,
	EmployeeSubject,
	 ClassSubject,
	'' AS EmployeeSNSubject,
	ISNULL(Convert(smallint,(select Isnull(max(cast(IsBreak as smallint)),0)*2+ISNULL(max(cast(IsBreakBefore as smallint)),0)*1
			From sTimetable.tTimeTableTime
			where TimeTableSchemaId=@rTimeTableSchemaId AND LectureNumber=A.LactureNumber
			Group by TimeTableSchemaId,LectureNumber)),0) AS HideBreak ,
	'' AS SubjectEmployeeSN,			--add for 27992 mantis
	'' AS SubjectName, --#Start Mantis : 0029066
	Convert(bit,0) AS DisplayWithBreak,
	Convert(bit,0) AS DisplayWithTeacher, --#End Mantis : 0029066
	'' AS SubjectCodeEmployeeSN,           -- add for mantis : 0034746
	'' AS ClassDivisionSubjectTeacher, --Added by dhananjay for mantis - 0035030
	'' AS BreakTime -- Mantis Id : 0042166
	,A.ClassOrderIndex--mantis : 0044760
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

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

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

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

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

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

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

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

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

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	ISNULL(A.ClassDivisionName,'')AS ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	A.IsPresent,
	'' As WeekOffs,
	0 As FromTime,
	0 As ToTime,
	'' as DivisionIncharge,
	A.EmployeeSubject,
	'' as ClassSubject,
	'' AS SubjectEmployeeSN,		--add for 27992 mantis
	'' AS SubjectName, --#Start Mantis : 0029066
	Convert(bit,0) AS DisplayWithBreak,
	Convert(bit,0) AS DisplayWithTeacher, --#End Mantis : 0029066
	'' AS SubjectCodeEmployeeSN,           -- add for mantis : 0034746
    '' AS ClassDivisionSubjectTeacher,--Added by dhananjay for mantis - 0035030
	'' AS BreakTime	-- Mantis Id : 0042166
	,A.ClassOrderIndex--mantis : 0044760
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EAR.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	'' AS TimeTableDetail,
	ISNULL(EAR.IsPresent,0) AS IsPresent,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' + case when ISNULL(EAR1.IsPresent,0)=0 then   ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)),'') +' <br><b> '+SM1.Title+'</b>','')

 else '' end
			FROM sTimetable.tTimeTable T1 
			Left join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			left JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR1 ON EAR1.EmployeeId = Em1.Id
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			AND (EAR1.AttendanceDate = @rDate OR @rDate = '')
			AND (T1.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, '')) EmployeeSubject
	,ISNULL(CM.OrderIndex,0) AS ClassOrderIndex--mantis : 0044760
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	--ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber),'') AS TimeTableDetail
	FROM 
	sTimetable.tTimeTable TT	 
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
	RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

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

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

	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TTD.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(EAR.IsPresent,'') As IsPresent,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT   ',<br>' +case when ISNULL(EAR1.IsPresent,0)=0 then ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)),'') +' <br><b> '+SM1.Title+'</b>','') 

else '' end
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR1 ON EAR1.EmployeeId = Em1.Id
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			AND (EAR1.AttendanceDate = @rDate OR @rDate = '')
			AND (T1.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, '')) EmployeeSubject
	,ISNULL(CM.OrderIndex,0) AS ClassOrderIndex--mantis : 0044760
	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
	LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

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

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

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

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,1) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	DivisionIncharge,
	IsBreak,
	IsBreakBefore,
	EmployeeSubject,
	ClassSubject,
	EmployeeSNSubject,
	ISNULL(Convert(smallint,(select Isnull(max(cast(IsBreak as smallint)),0)*2+ISNULL(max(cast(IsBreakBefore as smallint)),0)*1
			From sTimetable.tTimeTableTime
			where TimeTableSchemaId=@rTimeTableSchemaId AND LectureNumber=A.LactureNumber
			Group by TimeTableSchemaId,LectureNumber)),0) AS HideBreak,
	A.SubjectEmployeeSN,			--add for 27992 mantis
	A.SubjectName, -- #Start Mantis : 0029066
	@rDisplayWithBreak AS DisplayWithBreak,
	@rDisplayWithTeacher AS DisplayWithTeacher, -- #End Mantis : 0029066
	A.SubjectCodeEmployeeSN,   -- add for mantis : 0034746
	ClassDivisionSubjectTeacher, ----Added by dhananjay for mantis - 0035030
	BreakTime			-- Mantis Id : 0042166
	,A.ClassOrderIndex --mantis : 0044760

FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(EM.LastName+' '+EM.FirstName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,'') As FromTime,
	ISNULL(TTM.ToTime,'') As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	(SELECT ISNULL(EM.FirstName+' '+EM.LastName,'') FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tDivisionMaster DIE ON DIE.InchargeEmployeeId = EM.Id  WHERE DIE.Id = DV.Id) as DivisionIncharge,
		
	--GetBreak
	CASE WHEN 
	(SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1) = 1 
	THEN (SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1)
	ELSE ISNULL(TT.IsBreak,0) END AS IsBreak,

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

	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ', ' +  ISNULL('<b>'+SM1.Title+'</b><br/>'+ISNULL(Em1.ShortName,''),'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '')) SubjectEmployeeSN,			--add for 27992 mantis
			[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' +  ISNULL(SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, ''))  SubjectName, -- #Mantis : 0029066
			[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ', ' +  ISNULL('<b>'+SM1.Code+'</b><br/>'+ISNULL(Em1.ShortName,''),'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '')) SubjectCodeEmployeeSN	, --add for mantis : 0034746
			
			--Added by dhananjay for mantis - 0035030
			[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ', ' +  ISNULL('<b>'+Em1.ShortName+'</b><br/>'+ISNULL(SM1.Title,''),'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '')) ClassDivisionSubjectTeacher,
			--Added by dhananjay for mantis - 0035030
			(SELECT Top 1 ISNULL(FromTime,'') + '-' + ISNULL(ToTime,'') FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
			AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND (IsBreak = 1 OR IsBreakBefore = 1)) AS BreakTime	-- Mantis Id : 0042166
			,ISNULL(CM.OrderIndex,0) AS ClassOrderIndex --mantis : 0044760
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0	
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DV.OrgId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	  AND (OM.Id = @rOrgId OR @rOrgId = 0)
	  AND TT.EmployeeId <> 0
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
		END
END
GO
PRINT N'Creating Procedure [sAlert].[pEmployeeBookIssueGet]...';


GO
CREATE PROCEDURE [sAlert].[pEmployeeBookIssueGet]
	 	 
		 @rBookIssueId bigint,
	 	 @rLibraryId int,
	 	 @rBatchId int,	 	 	 	
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),	 	
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select
			LM.OrgGroupId,
			EC.OrgId,
			EC.EmployeeId,
			EC.Code,
			EC.EmployeeName,
			EC.MobileNumber AS MobileNumber,
			ISNULL(EC.CompanyEmail,'') AS EmailId,
			ISNULL(EC.PhoneNoCompany,'') AS PhoneNoCompany,
			ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),			
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[LibraryName]',LM.Title),
			'[IssueDate]',BL.LogDate),
			'[DueDate]',BL.DueDate)
			 AS MsgText,
			95 AS SourceTypeId,
			EC.EmployeeId AS SourceId,
			@rMailSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			BM.Code AS BookCode,
			BM.Title AS BookName,
			LM.Title AS LibraryName,
			BL.LogDate AS IssueDate,
			EC.WhatsAppContactNo
		
		
	From 
		sHrm.vEmployeeCommonDetail EC
		INNER JOIN sLibrary.tBookLog BL ON BL.ReaderSourceId=EC.EmployeeId AND BL.ReaderSourceTypeId=95 AND BL.IsCurrentStatus=1 AND BL.StatusId=523 
		INNER JOIN sLibrary.tLibraryMaster LM on LM.Id=BL.LibraryId
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId AND BL.ResourceSourceTypeId=2009
	WHERE
		  BL.Id=@rBookIssueId 
		  AND BL.LibraryId=@rLibraryId
		  AND(EC.OrgId=@rOrgId)
		  AND (BL.BatchId=@rBatchId)
		  AND (EC.EmployeeStatusId=7) 
	
END
GO
PRINT N'Creating Procedure [sAlert].[pStockIssueEmployee]...';


GO
 
CREATE PROCEDURE [sAlert].[pStockIssueEmployee]
	 	 
		 @rStockIssueId nvarchar(max),
	 	 @rIssueDate Date,
		 @rIssueItem nvarchar(max),
		 @rSourceId BigInt, 	 	
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),	 	
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 

			OM.OrgGroupId,
			EC.OrgId,
			EC.EmployeeId,
			EC.Code,
			EC.EmployeeName,
			EC.MobileNumber AS MobileNo,	
			EC.CompanyEmail AS EmailId,
			replace(
			replace(
			replace (
			replace (
			replace(@rTemplate,'[IssueNo]',@rStockIssueId),			
			'[IssueDate]',@rIssueDate),
			'[IssueItem]',@rIssueItem),
			'[Department]',EC.DepartmentName),
			'[Name]',EC.EmployeeName)
			 AS MsgText,
			'95' AS SourceTypeId,
			EC.EmployeeId AS SourceId,
			@rMailSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			@rStockIssueId AS IssueNo,
			@rIssueDate AS IssueDate,
			@rIssueItem AS IssueItem,
			EC.WhatsAppContactNo
		
	From 
		[sHrm].[vEmployeeCommunication] EC
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
	WHERE
	
		 (EC.OrgId=@rOrgId)
		AND (EC.StatusId=7) AND EC.IsOtherUser=0	
		AND (EC.EmployeeId = @rSourceId)
	
END
GO
PRINT N'Creating Procedure [sFee].[pOrganizationwiseOldFeeDataGet]...';


GO
CREATE PROCEDURE [sFee].[pOrganizationwiseOldFeeDataGet]
	
	@rOldOrgGroupBatchId int,
	@rNewOrgGroupBatchId int,
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldAdmissionCategoryId int,
	@rNewAdmissionCategoryId int,
	@rOldReceiptBookId int,
	@rNewReceiptBookId int,
	@rOldOrgId int,
	@rNewOrgId int,
	@rFeeId int,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 
	IF OBJECT_ID('tempdb..#TempOldFeeImport') IS NOT NULL DROP TABLE #TempOldFeeImport

	DECLARE @lCount int
	-- Old Fee Import Temp Table
	CREATE TABLE #TempOldFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[Code] nvarchar(20),
		[Name] nvarchar(300),
		[RollNo] int,
		[ClassDivision] nvarchar(300),
		[PendingAmount] decimal(12,2) NULL,
		[Status] nvarchar(max) NULL
	)
	-- End Old Fee Import Temp Table
	
	INSERT INTO #TempOldFeeImport 
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		SA.Code,
		SA.Name,
		SA.RollNo,
		ISNULL(SA.ClassName, '') + ' - ' + ISNULL(SA.DivisionName, '') AS ClassDivision,
		SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount
		,''
  FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				SA1.Code,
				SA1.ClassName,
				SA1.DivisionName,
				SA1.RollNo,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOldOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOldOrgGroupBatchId 
			    AND ((FS1.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
			    AND ((FS1.ReceiptBookId=@rOldReceiptBookId) OR (@rOldReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND	((SA1.OrgId=@rOldOrgId) OR (@rOldOrgId=0))
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				SA1.Code,
				SA1.ClassName,
				SA1.DivisionName,
				SA1.RollNo,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOldOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOldOrgGroupBatchId 
		        AND ((FS1.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
		        AND ((FS1.ReceiptBookId=@rOldReceiptBookId) OR (@rOldReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))	
				AND	((SA1.OrgId=@rOldOrgId) OR (@rOldOrgId=0))
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOldOrgId) OR (@rOldOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOldOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOldOrgGroupBatchId)
				AND ((R.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				 
	WHERE	
			SA.OrgGroupBatchId = @rOldOrgGroupBatchId
			AND SA.OrgId = @rOldOrgId 
			AND SA.BatchId=@rOldBatchId
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			GROUP BY SA.StudentId,SA.AcademicId,SA.Name,SA.Code,SA.ClassName,SA.DivisionName,SA.RollNo
	
	SELECT @lCount = COUNT(AutoId) FROM #TempOldFeeImport
	
	BEGIN TRANSACTION
		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lAcademicId bigint = NULL
			DECLARE @lStudentId bigint = NULL
			DECLARE @lReferenceStudentId bigint = NULL
			DECLARE @lClassId int = NULL
			DECLARE @lFeeSetupId int = NULL
			DECLARE @lPendingAmount decimal(12,2)
			
			SELECT @lStudentId = StudentId,@lPendingAmount=PendingAmount FROM #TempOldFeeImport WHERE AutoId = @lCount
			SELECT @lStudentId = Id FROM sStudent.tStudentMaster  WHERE ReferenceSourceId =@lStudentId

			SELECT @lAcademicId = Id, @lClassId=ClassId FROM  sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
			SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND AdmissionCategoryId = @rNewAdmissionCategoryId AND BatchId=@rNewBatchId AND FeeId = @rFeeId AND ReceiptBookId = @rNewReceiptBookId
			
			IF @lAcademicId IS NULL 
			BEGIN
				UPDATE #TempOldFeeImport SET Status = 'Student not exists in new Organization' WHERE AutoId = @lCount
			END
			
			ELSE IF @lAcademicId IS NOT NULL AND @lFeeSetupId IS NOT NULL AND @lClassId IS NOT NULL
			BEGIN
				DECLARE @lIsReceiptGenerated bit = 0
				SET @lIsReceiptGenerated = (
					SELECT 1 FROM 
					sFee.tReceipt R
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SA ON R.SourceId = SA.AcademicId AND SA.BatchId = @rNewBatchId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.BatchId = @rNewBatchId 
					AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId AND FS.FeeId = @rFeeId 
					AND FS.ReceiptBookId = @rNewReceiptBookId
					AND R.SourceId = @lAcademicId
					)

				IF(@lIsReceiptGenerated = 1)
				BEGIN
					UPDATE #TempOldFeeImport SET Status = 'Receipt Generated or Fee Already Paid in New Batch'  WHERE AutoId = @lCount
				END
			END
			ELSE
			BEGIN
			print 3
				UPDATE #TempOldFeeImport SET Status = 'Fee Setup not assigned in New Batch' WHERE AutoId = @lCount
			END
			SET @lCount = @lCount -1
		END
		SELECT * FROM #TempOldFeeImport
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		DROP TABLE #TempOldFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, ERROR_LINE(), ERROR_MESSAGE()
	END CATCH
END
GO
PRINT N'Creating Procedure [sHrm].[pEmployeeDataUpdatetoProperCase]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeDataUpdatetoProperCase]
	@rId int
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	IF(@rId = 1)
	BEGIN
		UPDATE sHrm.tEmployeeMaster SET FirstName = ISNULL(sCommon.f_GetCamelCase(FirstName),''), MiddleName = ISNULL(sCommon.f_GetCamelCase(MiddleName),'')
			, LastName = ISNULL(sCommon.f_GetCamelCase(LastName),''), ShortName = ISNULL(sCommon.f_GetCamelCase(ShortName),'')
	END

	IF(@rId = 2)
	BEGIN
		UPDATE sHrm.tEmployeeJobDetail SET JobRemark = ISNULL(sCommon.f_GetCamelCase(JobRemark),''), ReasonOfleaving = ISNULL(sCommon.f_GetCamelCase(ReasonOfleaving),'')
			,ReferenceRemark = ISNULL(sCommon.f_GetCamelCase(ReferenceRemark),''), Subjects = ISNULL(sCommon.f_GetCamelCase(Subjects),'')
	END

	IF(@rId = 3)
	BEGIN
		UPDATE [sHrm].[tEmployeePersonalDetail] SET IdentificationMark1 = ISNULL(sCommon.f_GetCamelCase(IdentificationMark1),'')
		,Qualification = ISNULL(sCommon.f_GetCamelCase(Qualification),'')
		,FamilyCast = ISNULL(sCommon.f_GetCamelCase(FamilyCast),'')
	END

	IF(@rId = 4)
	BEGIN
		UPDATE [sHrm].[tEmployeeCommunications] SET PresentStreetOne = ISNULL(sCommon.f_GetCamelCase(PresentStreetOne),'')
		,PresentStreetTwo = ISNULL(sCommon.f_GetCamelCase(PresentStreetTwo),''), PresentStreetThree = ISNULL(sCommon.f_GetCamelCase(PresentStreetThree),'')
		,PresentCountry = ISNULL(sCommon.f_GetCamelCase(PresentCountry),''), PresentState = ISNULL(sCommon.f_GetCamelCase(PresentState),'')
		,PermanentStreetOne = ISNULL(sCommon.f_GetCamelCase(PermanentStreetOne),''), PresentCity = ISNULL(sCommon.f_GetCamelCase(PresentCity),'')
		,PresentZipCode = ISNULL(sCommon.f_GetCamelCase(PresentZipCode),''),PresentContactNo = ISNULL(sCommon.f_GetCamelCase(PresentContactNo),'')
		,PermanentStreetTwo = ISNULL(sCommon.f_GetCamelCase(PermanentStreetTwo),''), PermanentStreetThree = ISNULL(sCommon.f_GetCamelCase(PermanentStreetThree),'')
		,PermanentCountry = ISNULL(sCommon.f_GetCamelCase(PermanentCountry),''), PermanentState = ISNULL(sCommon.f_GetCamelCase(PermanentState),'')
		,PermanentCity = ISNULL(sCommon.f_GetCamelCase(PermanentCity),''), PermanentZipCode = ISNULL(sCommon.f_GetCamelCase(PermanentZipCode),'')
		,PermanentContactNo = ISNULL(sCommon.f_GetCamelCase(PermanentContactNo),''), EmergencyStreetOne = ISNULL(sCommon.f_GetCamelCase(EmergencyStreetOne),'')
		,EmergencyStreetTwo = ISNULL(sCommon.f_GetCamelCase(EmergencyStreetTwo),''), EmergencyStreetThree = ISNULL(sCommon.f_GetCamelCase(EmergencyStreetThree),'')
		,EmergencyCountry = ISNULL(sCommon.f_GetCamelCase(EmergencyCountry),''),EmergencyState = ISNULL(sCommon.f_GetCamelCase(EmergencyState),'')
		,EmergencyCity = ISNULL(sCommon.f_GetCamelCase(EmergencyCity),''), EmergencyZipCode = ISNULL(sCommon.f_GetCamelCase(EmergencyZipCode),'')
		,EmergencyContactNo = ISNULL(sCommon.f_GetCamelCase(EmergencyContactNo),''), CompanyEmail = ISNULL(sCommon.f_GetCamelCase(CompanyEmail),'')
		,PersonalEmail = ISNULL(sCommon.f_GetCamelCase(PersonalEmail),''), PhoneNoCompany = ISNULL(sCommon.f_GetCamelCase(PhoneNoCompany),'')
		,ExtensionNo = ISNULL(sCommon.f_GetCamelCase(ExtensionNo),''), MobileNumber = ISNULL(sCommon.f_GetCamelCase(MobileNumber),'')
		,WhatsAppContactNo = ISNULL(sCommon.f_GetCamelCase(WhatsAppContactNo),'')
	END

	IF(@rId = 5)
	BEGIN
		UPDATE [sHrm].[tEmployeeStatutoryAndOther] SET EPFNumber = ISNULL(sCommon.f_GetCamelCase(EPFNumber),''), ESINumber = ISNULL(sCommon.f_GetCamelCase(ESINumber),'')
			,BankName = ISNULL(sCommon.f_GetCamelCase(BankName),''), Branch = ISNULL(sCommon.f_GetCamelCase(Branch),''), IFSCNumber = ISNULL(sCommon.f_GetCamelCase(IFSCNumber),'')
			,AccountHolderName = ISNULL(sCommon.f_GetCamelCase(AccountHolderName),'')
	END
     
	IF(@rId = 6)
	BEGIN
		UPDATE [sHrm].[tEmployeePreviousEmployment] SET CompanyName = ISNULL(sCommon.f_GetCamelCase(CompanyName),''), Designation = ISNULL(sCommon.f_GetCamelCase(Designation),'')
			,Duration = ISNULL(sCommon.f_GetCamelCase(Duration),''), Remark = ISNULL(sCommon.f_GetCamelCase(Remark),'')
			,ReasonForLeaving = ISNULL(sCommon.f_GetCamelCase(ReasonForLeaving),'')	,JobDescription = ISNULL(sCommon.f_GetCamelCase(JobDescription),'')
	END

	IF(@rId=7)
	BEGIN
		UPDATE [sHrm].[tEmployeeQualification] SET ExamPassed = ISNULL(sCommon.f_GetCamelCase(ExamPassed),''), PassYear = ISNULL(sCommon.f_GetCamelCase(PassYear),'')
		,Grade = ISNULL(sCommon.f_GetCamelCase(Grade),''), InstituteDetail = ISNULL(sCommon.f_GetCamelCase(InstituteDetail),'')
		,BoardDetail = ISNULL(sCommon.f_GetCamelCase(BoardDetail),''),Subjects = ISNULL(sCommon.f_GetCamelCase(Subjects),'')
		, Remark = ISNULL(sCommon.f_GetCamelCase(Remark),'')
	END

	IF(@rId = 8)
	BEGIN
	UPDATE [sHrm].[tEmployeeFamilyDetails] SET Name = ISNULL(sCommon.f_GetCamelCase(Name),''), Occupation = ISNULL(sCommon.f_GetCamelCase(Occupation),'')
	,EmailId = ISNULL(sCommon.f_GetCamelCase(EmailId),'')
	END

END
GO
PRINT N'Creating Procedure [sSecurity].[pSMSPoviderIdApiGet]...';


GO
CREATE PROCEDURE [sSecurity].[pSMSPoviderIdApiGet] 
	@rOrgGroupId INT
	,@rOSTypeId INT = 0
	,@rPackageName NVARCHAR(100)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	IF EXISTS(SELECT 1 FROM sSecurity.tOrgGroupMobileApp WHERE OrgGroupId = @rOrgGroupId AND ISNULL(IsRestrictOtherAppLogin, 0) = 1)
	BEGIN
		SELECT 
			ISNULL(OGM.SMSProviderId, 0) AS SMSProviderId,
			ISNULL(DM.Title, '') AS LoginByTitle
		FROM sSecurity.tOrgGroupMobileApp OGM
		LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OGM.LoginById
			AND DM.DataTypeId = 12
		WHERE OGM.OrgGroupId = @rOrgGroupId
		AND OGM.PackageName = @rPackageName
	END
	ELSE
	BEGIN
		SELECT 
			ISNULL(OGM.SMSProviderId, 0) AS SMSProviderId,
			ISNULL(DM.Title, '') AS LoginByTitle
		FROM sSecurity.tOrgGroupMobileApp OGM
		LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OGM.LoginById
			AND DM.DataTypeId = 12
		WHERE OGM.OrgGroupId = @rOrgGroupId
	END
	
END
GO
PRINT N'Altering Procedure [sCommon].[pMasterDataAdd]...';


GO
ALTER  PROCEDURE [sCommon].[pMasterDataAdd]
	 
        
		@rTitle nvarchar(200)='',--mantis : 0044848 : nvarchar(100) to 200
		@rCode nvarchar(50)='',
		@rIsObsolete bit=0,
		@rCreatedUserId bigint,
		@rOrgGroupId smallint,
		@rOrgId int,
		@rTable_Name int=0,
		@rDependId int=0,
		@rNo int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lReligionId INT 
			 
		IF(@rTable_Name=1)
		BEGIN
		
			If Exists(select Id from sFinanceCommon.tBankMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFinanceCommon.tBankMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sFinanceCommon.tBankMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=2)
		BEGIN
		
			If Exists(select Id from sCommon.tReligionMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tReligionMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tReligionMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=3)
		BEGIN
		
			If Exists(select Id from sCommon.tOccupationMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tOccupationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tOccupationMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			
			IF(@rTable_Name=4)
		BEGIN
		
			If Exists(select Id from sCommon.tMotherTongueMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tMotherTongueMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tMotherTongueMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
		IF(@rTable_Name=5)
		BEGIN
		
			If Exists(select Id from sCommon.tPreviousSchoolMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tPreviousSchoolMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tPreviousSchoolMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=6)
		BEGIN
		
			If Exists(select Id from sHrm.tQualificationMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tQualificationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sHrm.tQualificationMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
				IF(@rTable_Name=7)
		BEGIN
		
			If Exists(select Id from sCommon.tCountryMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tCountryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tCountryMaster
			(
			
				Id,
				Title,
				Nationality,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rCode,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
				IF(@rTable_Name=8)
		BEGIN
			If Exists(select Id from sCommon.tStateMaster where Title=@rTitle AND CountryId=@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tStateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tStateMaster
			(
			
				Id,
				Title,
				CountryId,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
			
				IF(@rTable_Name=9)
		BEGIN
				If Exists(select Id from sCommon.tCityMaster where Title=@rTitle AND StateId =@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tCityMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tCityMaster
			(
			
				Id,
				Title,
				StateId,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
				IF(@rTable_Name=10)
		BEGIN
				If Exists(select Id from sCommon.tHobbyMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tHobbyMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tHobbyMaster
			(
			
				Id,
				Title,
				Code,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			 
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rCode,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
				 
			)
			END
			
		-- IF(@rTable_Name=11)
		--BEGIN
		--		If Exists(select Id from sCommon.tHostelMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
		--		BEGIN
		--		select -103 as Result
		--		RETURN
	 --		END 
	 --		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tHostelMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		--	INSERT INTO sCommon.tHostelMaster
		--	(
			
		--		Id,
		--		Title,
		--		Code,
		--		 IsObsolete,
		--		 OrgGroupId,
		--		CreatedUserId,
		--		UpdateduserId,
		--		CreatedDateTime,
		--		UpdatedDateTime 
			 
		--	)
		--VALUES
		--	(
		--		@lNextNumber,
				
		--		@rTitle,
		--		@rCode,
		--		 @rIsObsolete,
		--		 @rOrgGroupId,
		--		@rCreatedUserId,
		--		@rCreatedUserId,
		--		sCommon.fGetDate() ,
		--		sCommon.fGetDate() 
				 
		--	)
		--	END
		 
		 	
		 IF(@rTable_Name=11)
		BEGIN
				If Exists(select Id from sCommon.tAreaMaster where Title=@rTitle AND CityId =@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tAreaMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tAreaMaster
			(
			
				Id,
				Title,
				CityId,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime,
				IsShow
			 
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
				
				 
			)
			END
		 
		  IF(@rTable_Name=12)
		BEGIN
				If Exists(select Id from sCommon.tFamiliyCastMaster where FamiliyCast=@rTitle AND CastCategoryId=@rDependId AND OrgGroupId=@rOrgGroupId)	--add CastCategoryId
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		
	  
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tFamiliyCastMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tFamiliyCastMaster
			(
			
				Id,
				FamiliyCast, 
				 FamiliySubCast, 
				 OrgGroupId,
				 IsObsolete,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime,
				CastCategoryId,		--added
				ReligionId			--added
			 
			 
			)
		VALUES
			(
				@lNextNumber,
				@rTitle, 
				@rCode,
				 @rOrgGroupId,
				 @rIsObsolete,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate(),
				@rDependId,			--added
				-1					--added
				 
				
				 
			)
			END
			
			
			
			 IF(@rTable_Name=13	)
		BEGIN
		If Exists(select Id from sSetup.tSubjectMaster where Code=@rCode AND OrgId=@rOrgId)			--add if condition
			BEGIN
			select -102 as Result
			RETURN
		END
				If Exists(select Id from sSetup.tSubjectMaster where Title=@rTitle   AND OrgId=@rOrgId)
				BEGIN
				select -103 as Result
				RETURN
				END
				If Exists(select Id from sSetup.tSubjectMaster where Number=@rNo and OrgId=@rOrgId)		--add if condition
			BEGIN
			select -104 as Result
			RETURN
	 		END 
	 		
	  
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sSetup.tSubjectMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sSetup.tSubjectMaster
			(
			
				Id,
				Code, 
				 Number, 
				 Title,
				 IsObsolete,
				 OrgId,
				 OrderIndex,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			 
			 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rNo,
				@rTitle, 
				 @rIsObsolete,
				 @rOrgId,
				 @rNo,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate()  
				 
				
				 
			)
			END
			
			
			SELECT 1 AS Result
			
			
		 
 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAccounting].[pExpenseAdd]...';


GO
ALTER   PROCEDURE [sAccounting].[pExpenseAdd]
	@rRemark [nvarchar](100),
	@rCreatedUserId [bigint],
    --@rIsObsolete [bit],
	@rExpenseDate Date,
	@rExpenseGroupId [int],
	@rOrgId smallint,
	@rStoreLocationId int,
	@rAmount decimal(12,2)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF NOT EXISTS (SELECT 1 FROM sAccounting.tExpense WHERE UPPER(ExpenseDate) = UPPER(@rExpenseDate) AND ExpenseGroupId = @rExpenseGroupId AND OrgId = @rOrgId)

BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tExpense', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sAccounting.tExpense
		(
			Id,
			Amount,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			--IsObsolete,
			UpdatedUserId,
			UpdatedDateTime,
			ExpenseDate,
			ExpenseGroupId,
			OrgId
			--,StoreLocationId  --Commented on 19/06/2025 - No StoreLocationId in table
		)
	VALUES
		(
			@lNextNumber,
			@rAmount,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			--@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rExpenseDate,
			@rExpenseGroupId,
			@rOrgId
			--,@rStoreLocationId		--Commented on 19/06/2025 - No StoreLocationId in table
		)
	SELECT 1 AS RESULT
END
ELSE
 BEGIN
 SELECT -100 AS RESULT
 END
END
GO
PRINT N'Altering Procedure [sCommunication].[pXMLCircularAdd]...';


GO
ALTER PROCEDURE [sCommunication].[pXMLCircularAdd]
	
	@rXML nvarchar(max),
	@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
	BEGIN TRY					-- Uncommented for mantis 0032762
	
	BEGIN TRANSACTION			-- Uncommented for mantis 0032762
	
	DECLARE @lOrgGroupId int = 0

	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	 
	SET @rXML=REPLACE(@rXML,'&','AND')
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,
			@intDoc INT
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXML
	
	DECLARE @lNextNumber BIGINT  
	DECLARE @lFromNextNumber BIGINT  
	EXECUTE sCommon.pTableRowIdGet @lOrgGroupId, 'sCommunication.tCircular', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	SET @lFromNextNumber=@lNextNumber-1
	INSERT INTO sCommunication.tCircular
		(
			Id,
			Title,
			Remark,
			StartDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			OrgGroupBatchId,
			AssigneeId,
			CircularTypeId,
			PublishDateTime
		)
	SELECT
			@lFromNextNumber + ROW_NUMBER() OVER(ORDER BY SourceId),
			Title,
			Remark,
			sCommon.fGetDate(), 
			CreatedUserId,
			sCommon.fGetDate(), 
			OrgGroupId,
			OrgGroupBatchId,
			AssigneeId,
			sCommon.fGetIntIdForOrg(2,@lOrgGroupId),
			sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/Circular', 1)
	WITH
	(
		SourceId bigint 'SourceId',
		Title nvarchar(200) 'Title',
		Remark nvarchar(MAX) 'Remark', -- changes for mantis id:0045204
		CreatedUserId bigint 'CreatedUserId',
		OrgGroupId smallint 'OrgGroupId',
		OrgGroupBatchId int 'OrgGroupBatchId',
		AssigneeId tinyint 'AssigneeId',
		SourceTypeId smallint 'SourceTypeId'
	)
	
	
	INSERT INTO sCommunication.tCircularScope
		(
			CircularId,
			SourceTypeId,
			SourceId,
			AssigneeToId
		)
	SELECT
			@lFromNextNumber + ROW_NUMBER() OVER(ORDER BY SourceId),
			SourceTypeId,
			SourceId,
			AssigneeToId
					
	FROM OPENXML (@intDoc, '/Table/Circular', 1)
	WITH
	(
		SourceId bigint 'SourceId',
		SourceTypeId smallint 'SourceTypeId',
		AssigneeToId smallint 'AssigneeToId'
	)
	
	
	SELECT @lCount = COUNT(1) FROM OPENXML (@intDoc, '/Table/Circular', 1)
				 WITH ( AcademicId bigint)
		SET @lNextNumber  = @lCount + @lFromNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @lOrgGroupId, @rTableTitle = 'sCommunication.tCircular', @rCurrentNumber = @lNextNumber 
		
		EXEC sp_xml_removedocument @intDoc
		
		SELECT 1 AS Result,@lFromNextNumber+1 AS FromId,@lNextNumber AS ToId
	
		COMMIT TRANSACTION		-- Uncommented for mantis 0032762
								
	END TRY						-- Uncommented for mantis 0032762
						
	BEGIN CATCH 				-- Uncommented for mantis 0032762
		ROLLBACK TRANSACTION	-- Uncommented for mantis 0032762
		SELECT -1 AS Result		-- Uncommented for mantis 0032762
	END CATCH					-- Uncommented for mantis 0032762
END

GO
PRINT N'Update complete.';
GO

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